#!/bin/sh
# Quick and dirty script to install apps from .iso files
# Adapted from winetricks as of r995
# Copyright 2007, 2008, 2009, 2010 Google (Dan Kegel, dank@kegel.com)
# Copyright 2008, 2009, 2010 Austin English (austinenglish@gmail.com)
# License: LGPL (for compatibility with winehq)
# Please report problems at http://code.google.com/p/winezeug/issues
# Note to contributors: please avoid gnu extensions in this shell script,
# as it has to run on MacOSX and Solaris, too.  A good book on the topic is
# "Portable Shell Programming" by Bruce Blinn

#---- Constants -------------------------------------------------

# Name of this version of wisotool (YYYYMMDD)
VERSION=20100530

early_wine()
{
    WINEDLLOVERRIDES=mshtml= $WINE "$@"
}

# Default values for important settings if not already in environment.
# These settings should not need editing here.
case "$OS" in
 "Windows_NT")
    # Cheezy fix for getting rid of double slashes when running cygwin in wine
    case "$HOME" in
      /) HOME="" ;;
    esac
    WINE=""
    WINEPREFIX="${WINEPREFIX:-$HOME/.wine}"
    DRIVE_C="C:/"
    XXXPATH=cygpath
    ;;
 *)
    WINE=${WINE:-wine}
    WINEPREFIX="${WINEPREFIX:-$HOME/.wine}"
    DRIVE_C="$WINEPREFIX/dosdevices/c:"
    XXXPATH="early_wine winepath"
    # FIXME: does id work on mac/solaris?
    USERID=`id -u`
    ;;
esac

WISOTOOL_DIR=${WISOTOOL_DIR:-$HOME/.wisotool}

# You can add your own verb to wisotool by creating $WISOTOOL_VERBS/foo.verb
WISOTOOL_VERBS="${WISOTOOL_VERBS:-$WISOTOOL_DIR/verbs}"
mkdir -p "$WISOTOOL_VERBS"

# Postinstall scripts, if any, go here
WISOTOOL_POST="${WISOTOOL_POST:-$WISOTOOL_DIR/postinstall}"

# Internal variables; these locations are not too important
WISOTOOL_CACHE="${WISOTOOL_CACHE:-$HOME/.wisotoolcache}"
test -d "$WISOTOOL_CACHE" || WISOTOOL_CACHE="$WISOTOOL_DIR/cache"
WISOTOOL_CACHE_WIN="`$XXXPATH -w $WISOTOOL_CACHE | tr '\012' ' ' | sed 's/ $//'`"
WISOTOOL_TMP="$DRIVE_C"/wisotooltmp
WISOTOOL_TMP_WIN='c:\wisotooltmp'

# Clean up after failed runs, if needed
rm -rf "$WISOTOOL_TMP"
mkdir -p "$WISOTOOL_TMP"

# Handle case where z: doesn't exist
if test "$WISOTOOL_CACHE_WIN" = ""
then
    # WISOTOOL_CACHE isn't accessible via a drive letter mapping, so make one,
    # but be sure to clean it up later.
    for letter in y x w v u t s r q
    do
        if ! test -d "$WINEPREFIX"/dosdevices/${letter}:
        then
            WISOTOOL_CACHE_SYMLINK="$WINEPREFIX"/dosdevices/${letter}:
            ln -sf "$WISOTOOL_CACHE" "$WISOTOOL_CACHE_SYMLINK"
            break
        fi
    done
fi

USERNAME=${USERNAME:-$LOGNAME}

# Overridden for windows
ISO_MOUNT_ROOT=/mnt/wisotool
ISO_MOUNT_LETTER=i

WINDIR="$DRIVE_C/windows"

#---- Functions -------------------------------------------------

# Detect which sudo to use
detect_sudo() {
    SUDO=sudo
    test "$GUI" = 1 || return
    if test x"$DISPLAY" != x""
    then
        if test -x "`which gksudo 2>/dev/null`"
        then
            SUDO=gksudo
        elif test -x "`which kdesudo 2>/dev/null`"
        then
            SUDO=kdesudo
        fi
    fi
}

# Detect which menu program to use
detect_menu() {
    # TODO: add 'dialog'
    MENU=xmessage
    if test -x "`which zenity 2>/dev/null`"
    then
        MENU=zenity
    elif test -x "`which kdialog 2>/dev/null`"
    then
        MENU=kdialog
    fi
}

warn() {
    echo "------------------------------------------------------"
    echo "$@"
    echo "------------------------------------------------------"

    test "$GUI" = 1 || return

    # For some reason, nulls were showing up in $@?!, causing truncated output in zenity
    msg="`echo $@ | tr '\000' ' '`"
    case $MENU in
    *zenity) zenity --error --title=Wisotool --text="$msg" --no-wrap;;
    *kdialog) kdialog --title Wisotool --error "$msg" ;;
    *xmessage) xmessage -title Wisotool -center "  Error: $msg  " ;;
    esac
}

die() {
    warn "$@"

    exit 1
}

# Abort if user doesn't own the given directory (or its parent, if it doesn't exist yet)
die_if_user_not_dirowner() {
    if test -d "$1"
    then
        checkdir="$1"
    else
        # fixme: quoting problem?
        checkdir=`dirname "$1"`
    fi
    nuser=`id -u`
    nowner=`ls -l -n -d -L "$checkdir" | awk '{print $3}'`
    if test x$nuser != x$nowner
    then
        die "You (`id -un`) don't own $checkdir. Don't run wisotool as another user!"
    fi
}

#----------------------------------------------------------------

usage() {
    set +x
    # WARNING: do not use single quote in any package description; that breaks the gui menu.
    echo "Script to install games automatically."
    echo "Usage: $0 [options] package [package] ..."
    echo ""
    echo "Options:"
    echo " -q         quieter"
    echo " -v         verbose"
    echo " -V         display Version"
    echo "Packages:"
    sort "$WISOTOOL_TMP"/menutext
    echo "Pseudopackages:"
    echo " load          Load a disc into the iso cache"
    echo " load=KEY      Load a disc with given key; only works from commandline at moment"

    # Show the other help message, too
    case $GUI in
    0) load_help ;;
    esac
}

#----------------------------------------------------------------
# Trivial GUI just to handle case where user tries running without commandline

kdialog_showmenu() {
    title="$1"
    shift
    text="$1"
    shift
    col1name="$1"
    shift
    col2name="$1"
    shift
    while test $# -gt 0
    do
        args="$args $1 $1 off"
        shift
    done
    kdialog --title "$title" --separate-output --checklist "$text" $args
}

xmessage_showmenu() {
    title="$1"
    shift
    text="$1"
    shift
    col1name="$1"
    shift
    col2name="$1"
    shift
    if test $# -gt 0
    then
        args="$1"
        shift
    fi
    while test $# -gt 0
    do
        args="$args,$1"
        shift
    done
    (echo "$title"; echo ""; echo "$text") | \
    xmessage -print -file - -buttons "Cancel,$args" | sed 's/Cancel//'
}

showmenu()
{
    # FIXME: call verblist_get_descriptions instead of scraping usage() ?
    case $MENU in
    zenity)
        echo "zenity --title 'Select a package to install' --text 'Install?' --list --checklist --column '' --column Package --column Description --height 440 --width 600 \\" > "$WISOTOOL_TMP"/zenity.sh
        usage | grep '^ [3a-z]' | sed 's/^ \([^ ]*\) *\(.*\)/FALSE "\1" '"'\2'/" | sed 's/$/ \\/' >> $WISOTOOL_TMP/zenity.sh
        todo="`sh "$WISOTOOL_TMP"/zenity.sh | tr '|' ' '`"
        ;;
    kdialog)
        packages=`usage | awk '/^ [3a-z]/ {print $1}'`
        todo="`kdialog_showmenu "wisotool" "Select a package to install" "Install?" "Package" $packages`"
        ;;
    xmessage)
        packages=`usage | awk '/^ [3a-z]/ {print $1}'`
        todo="`xmessage_showmenu "wisotool" "Select a package to install" "Install?" "Package" $packages`"
        ;;
    esac

    if test "$todo"x = x
    then
       exit 0
    fi
}

#-----  Helpers  ------------------------------------------------

# Execute with error checking
try() {
    # "VAR=foo try cmd" fails to put VAR in the environment
    # with some versions of bash if try is a shell function?!
    # Adding this explicit export works around it.
    export WINEDLLOVERRIDES
    echo Executing "$@"
    # Mark executable - needed if running on windows vista
    case "$1" in
    *.exe) chmod +x "$1" || true
      cmd /c "$@"
      ;;
    *)
      "$@"
      ;;
    esac
    status=$?
    if test $status -ne 0
    then
        die "Note: command '$@' returned status $status.  Aborting."
    fi
}

try_regedit() {
    # on windows, doesn't work without cmd /c
    case "$OS" in
    "Windows_NT") cmdc="cmd /c";;
    *) unset cmdc
    esac

    try early_wine $cmdc regedit "$@"
}

regedit() {
    die oops, bug, please report
}

try_cabextract() {
    # Not always installed, but shouldn't be fatal unless it's being used
    CABEXTRACT="`which cabextract 2>/dev/null`"
    if test ! -x "$CABEXTRACT"
    then
        die "Cannot find cabextract.  Please install it (e.g. 'sudo apt-get install cabextract' or 'sudo yum install cabextract')."
    fi

    try $CABEXTRACT "$@"
}

cabextract() {
    die oops, bug, please report
}

# At some point, make the return value controllable by a global 
# commandline option so we can see if we still need the workaround.
workaround_wine_bug()
{
    if test "$WINE" = ""
    then
        echo No need to work around wine bug $1 on windows
        return 1
    fi
    case $1 in
    "$WISOTOOL_BLACKLIST") 
        echo wine bug $1 workaround blacklisted, skipping
        return 1
        ;;
    esac
    warn Working around wine bug $1
    return 0
}

# verify an sha1sum
verify_sha1sum() {
    wantsum=$1
    file=$2

    gotsum=`$SHA1SUM < $file | sed 's/ .*//'`
    if [ "$gotsum"x != "$wantsum"x ]
    then
       die "sha1sum mismatch!  Rename $file and try again."
    fi
}

# Escape entities for URL usage
# Usage: url_encode < to_filter > filtered
# See RFC3986.
url_encode() {
    perl -e '
        while (<>) {
            s/\n//;
            s/([^A-Za-z0-9\-\._~])/sprintf("%%%02X", ord($1))/ge;
            print;
        }
    '
    return $?
}

# Download a file
# Usage: package url [sha1sum [filename [cookie jar]]]
# Caches downloads in wisotoolcache/$package
download() {
    if [ "$4"x != ""x ]
    then
        file="$4"
    else
        file=`basename "$2"`
    fi
    cache="$WISOTOOL_CACHE/$1"
    mkdir -p "$cache"
    if test ! -s "$cache/$file" && test -f "$cache/$file"
    then
        # zero size - bad download?
        rm "$cache/$file"
    fi
    if test "$nosizecheck" != "" || test ! -f "$cache/$file"
    then
        cd "$cache"
        # Mac folks tend to have curl rather than wget
        # On Mac, 'which' doesn't return good exit status
        # Need to jam in --header "Accept-Encoding: gzip,deflate" else
        # redhat.com decompresses liberation-fonts.tar.gz!
        echo Downloading $2
        if [ -x "`which wget 2>/dev/null`" ]
        then
           # Use -nd to insulate ourselves from people who set -x in WGETRC
           # [*] --retry-connrefused works around the broken sf.net mirroring
           # system when downloading corefonts
           # [*] --read-timeout is useful on the adobe server that doesn't
           # close the connection unless you tell it to (control-C or closing
           # the socket)
           # Disable retries for gog.com (which requires higher level retries)
           wget -O "$file" -nd -c --read-timeout=300 --tries=1 --retry-connrefused --header "Accept-Encoding: gzip,deflate" ${5:+--load-cookies "$5"} "$2"
        else
           # curl doesn't get filename from the location given by the server!
           # fortunately, we know it
           curl -L -o "$file" -C - --header "Accept-Encoding: gzip,deflate" ${5:+--cookie "$5"} "$2"
        fi
        if test $? != 0
        then
            test -f "$file" && rm "$file"
            die "Downloading $2 failed"
        fi
        # Need to decompress .exe's that are compressed, else cygwin fails
        # Only affects cygwin, so don't barf if 'file' not installed
        FILE=`which file 2>/dev/null`
        case $FILE-$file in
        /*-*.exe)
            case `file $file` in
            *gzip*) mv $file $file.gz; gunzip < $file.gz > $file;;
            esac
        esac

        # On cygwin, .exe's must be marked +x
        case $file in
        *.exe) chmod +x $file ;;
        esac

        cd "$olddir"
    fi
    if [ "$3"x != ""x ]
    then
        verify_sha1sum $3  "$cache/$file"
    fi
}

set_winver() {
    echo "Setting Windows version to $1"
    cat > "$WISOTOOL_TMP"/set-winver.reg <<_EOF_
REGEDIT4

[HKEY_CURRENT_USER\Software\Wine]
"Version"="$1"

_EOF_
    try_regedit "$WISOTOOL_TMP_WIN"\\set-winver.reg
}

set_app_winver() {
    app="$1"
    version="$2"
    echo "Setting $app to $version mode"
    (
    echo REGEDIT4
    echo ""
    echo "[HKEY_CURRENT_USER\\Software\\Wine\\AppDefaults\\$app]"
    echo "\"Version\"=\"$version\""
    ) > "$WISOTOOL_TMP"/set-winver.reg

    try_regedit "$WISOTOOL_TMP_WIN"\\set-winver.reg
    rm "$WISOTOOL_TMP"/set-winver.reg
}


load_vcdmount()
{
    if test "$WINE" != ""
    then
        return
    fi

    # Call only on real Windows.
    # Sets VCD_DIR and ISO_MOUNT_ROOT

    # The only free mount tool I know for Windows Vista is Virtual CloneDrive,
    # which can be downloaded at
    # http://www.slysoft.com/en/virtual-clonedrive.html
    # FIXME: actually install it here

    # Locate vcdmount.exe.
    VCD_DIR="Elaborate Bytes/VirtualCloneDrive"
    if test ! -x "$programfilesdir_unix/$VCD_DIR/vcdmount.exe" && test ! -x "$programfilesdir_x86_unix/$VCD_DIR/vcdmount.exe"
    then
        warn "Installing Virtual CloneDrive"
        download . http://static.slysoft.com/SetupVirtualCloneDrive.exe
        # have to use cmd else vista won't let cygwin run .exe's?
        chmod +x "$WISOTOOL_CACHE"/SetupVirtualCloneDrive.exe
        cd "$WISOTOOL_CACHE"
        cmd /c SetupVirtualCloneDrive.exe
        cd "$olddir"
    fi
    if test -x "$programfilesdir_unix/$VCD_DIR/vcdmount.exe"
    then
        VCD_DIR="$programfilesdir_unix/$VCD_DIR"
    elif test -x "$programfilesdir_x86_unix/$VCD_DIR/vcdmount.exe"
    then
        VCD_DIR="$programfilesdir_x86_unix/$VCD_DIR"
    else
        die "can't find Virtual CloneDrive?"
    fi
    # FIXME: Use WMI to locate the drive named
    # "ELBY CLONEDRIVE..." using WMI as described in
    # http://delphihaven.wordpress.com/2009/07/05/using-wmi-to-get-a-drive-friendly-name/
}

iso_mount()
{
    my_img="$1"
    iso_umount

    if test "$WINE" = ""
    then
        load_vcdmount
        my_img_win="`$XXXPATH -w $my_img | tr '\012' ' ' | sed 's/ $//'`"
        cd "$VCD_DIR"
        try vcdmount.exe /l=$letter "$my_img_win"
        cd "$olddir"

        tries=0
        while test $tries -lt 20
        do
            for ISO_MOUNT_LETTER in e f g h i j k
            do
                ISO_MOUNT_ROOT=/cygdrive/$ISO_MOUNT_LETTER
                if find $ISO_MOUNT_ROOT -iname 'setup*' -o -iname '*.exe' -o -iname '*.msi' 
                then
                    break 2
                fi
            done
            tries=`expr $tries + 1`
            echo "Waiting for mount to finish mounting"
            sleep 1
        done
    else
        # Linux
        case "$SUDO" in
        gksudo)
          try $SUDO "mkdir -p $ISO_MOUNT_ROOT"
          try $SUDO "mount -o ro,loop,uid=$USERID,unhide $my_img $ISO_MOUNT_ROOT"
          ;;
        *)
          try $SUDO mkdir -p $ISO_MOUNT_ROOT
          try $SUDO mount -o ro,loop,uid=$USERID,unhide "$my_img" $ISO_MOUNT_ROOT
          ;;
        esac
        echo "Mounting as drive ${ISO_MOUNT_LETTER}:"
        # Gotta provide a symlink to the raw disc, else installers that check volume names will fail
        # FIXME: one of these gives a warning frequently, possibly on second run
        ln -sf "$my_img" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}::"
        ln -sf "$ISO_MOUNT_ROOT" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}:"
    fi
}

iso_umount()
{
    if test "$WINE" = ""
    then
        # Windows
        load_vcdmount
        cd "$VCD_DIR"
        try vcdmount.exe /u
        cd "$olddir"
    else
        echo "Running $SUDO umount $ISO_MOUNT_ROOT"
        case "$SUDO" in
        gksudo)
          # -l lazy unmount in case executable still running
          $SUDO "umount -l $ISO_MOUNT_ROOT"
          try $SUDO "rm -rf $ISO_MOUNT_ROOT"
          ;;
        *)
          $SUDO umount -l $ISO_MOUNT_ROOT
          try $SUDO rm -rf $ISO_MOUNT_ROOT
          ;;
        esac
        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}:
        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}::
    fi
}

mds_mount()
{

    my_img="$1"
    mds_umount

    # FIXME: will vcdmount work for mds/mdf files on windows, or do we need to use Alcohol here as well?
    if test "$WINE" = ""
    then
        load_vcdmount
        my_img_win="`$XXXPATH -w $my_img | tr '\012' ' ' | sed 's/ $//'`"
        cd "$VCD_DIR"
        try vcdmount.exe /l=$letter "$my_img_win"
        cd "$olddir"
        while ! test -d "$ISO_MOUNT_ROOT"
        do
            echo "Waiting for mount to finish"
            sleep 1
        done
    else
        # Wine

        cdemu load 0 $my_img

        sleep 60

        # FIXME: This is messy, but AFAICT, there's no way in advance to know where the drive will be mounted,
        # since it depends on the cd/dvd title from the origial media, which is embedded in the mdf/mds file.
        # Unfortunately, cdemu doesn't give an easy way to determine it, so find it with a combination of
        # cdemu, mount, and grep
        device_name=`cdemu device-mapping | grep ^0 | awk '{print $2}'`
        ISO_MOUNT_ROOT=`mount -l | grep $device_name | awk '{print $3}'`

        echo "Mounting as drive ${ISO_MOUNT_LETTER}:"
        # Gotta provide a symlink to the raw disc, else installers that check volume names will fail
        # FIXME: one of these gives a warning frequently, possibly on second run
        ln -sf "$device_name" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}::"
        ln -sf "$ISO_MOUNT_ROOT" "$WINEPREFIX/dosdevices/${ISO_MOUNT_LETTER}:"
    fi
}

mds_umount()
{
    if test "$WINE" = ""
    then
        # Windows
        load_vcdmount
        cd "$VCD_DIR"
        try vcdmount.exe /u
        cd "$olddir"
    else
        if [ ! -x "`which cdemu 2>/dev/null`" ]
        then
            die "cdemu is not installed, can't mount .mds files!"
        fi
        
        # Initialize cdemu, if not already:

        # FIXME: Not sure this is 100% accurate...
        # FIXME: Should kill the cdemud session when done...
        pgrep cdemud
        cdemud_run=$?
        case $cdemud_run in
        0) echo "cdemud is already running" ;;
        1) echo "cdemud is not running, let's start one" ;
           ( cdemud -b session & ) ;
           sleep 60
           # FIXME: grep for "cdemu0: Daemon: error while performing ioctl" and die if it shows up ;
        ;;
        *) die "unknown error in cdemud_run" ;;
        esac

        # FIXME: just running 'cdemu unload 0' doesn't seem to unload, but running 'eject /media/foo' does?
        cdemu unload 0
        # Check that nothing is loaded there:
        img_name=`cdemu status | grep ^0 | awk '{print $3}'`
        if [ "$img_name" != "N/A" ]
        then
            echo "$img_name is mounted in cdemu, forcing an eject"
            device_name=`cdemu device-mapping | grep ^0 | awk '{print $2}'`
            ISO_MOUNT_ROOT=`mount -l | grep $device_name | awk '{print $3}'`
            # FIXME: Does this need sudo?
            eject $ISO_MOUNT_ROOT
            sleep 60 # Give devices time to settle
        fi

        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}:
        rm -f "$WINEPREFIX"/dosdevices/${ISO_MOUNT_LETTER}::
    fi
}

#----------------------------------------------------------------

# Executed if user kills script
cleanup()
{
  echo "Caught signal, cleaning up."
  case "$pid" in
  "") ;;
  *) kill $pid ;;
  esac
  # TODO: merge this with cleanup code at end of script
  test "$WISOTOOL_CACHE_SYMLINK" && rm -f "$WISOTOOL_CACHE_SYMLINK"
  echo "Done cleanup, quitting."
  exit 1
}

# FIXME: add support for ripping mdf/mds with Alcohol 120%
load_iso() {
   method=$1
   key="$2"

   die_if_user_not_dirowner "$WISOTOOL_CACHE"

   # Detect raw device
   dev=/dev/null
   for dev in /dev/cdrom /dev/sr0
   do
       test -b $dev && break
   done
   test $dev = /dev/null && die "can't find cd/dvd drive"

   # Hack for Gentoo - make sure we can read from the drive
   test -r $dev || sudo chmod 666 $dev

   # Wait for user to insert disc
   while ! dd if=$dev of=/dev/null count=1
   do
     sleep 1
   done

   # Copy disc to .iso file, display progress every 5 seconds
   # Use conv=noerror,sync to replace unreadable blocks with zeroes
   case $method in
   dd) 
     dd if=$dev of="$WISOTOOL_CACHE"/temp.iso bs=2048 conv=noerror,sync &
     pid=$!
     ;;
   ddrescue) 
     if test `which ddrescue` = ""
     then
         die "Please install ddrescue first."
     fi
     ddrescue -v -b 2048 $dev "$WISOTOOL_CACHE"/temp.iso &
     pid=$!
     ;;
   esac

   # Since we're running dd in the background, register a handler to kill it if user presses ^C
   trap cleanup 1 2 3 6
   while ps -p $pid > /dev/null 2>&1
   do
     sleep 5
     ls -l "$WISOTOOL_CACHE"/temp.iso
   done
   pid=""

   echo "Computing sha1sum..."
   # FIXME: can't handle spaces in "$WISOTOOL_CACHE"
   sum=`sha1sum "$WISOTOOL_CACHE"/temp.iso | awk '{print $1}'`
   echo "Sha1sum of iso is $sum"
   
   mv "$WISOTOOL_CACHE"/temp.iso "$WISOTOOL_CACHE"/$sum.iso
   if test "$key" != ""
   then
       # FIXME: in gui, prompt user for key if load= was chosen?
       echo "$key" > "$WISOTOOL_CACHE"/$sum.txt
   fi

   # Note: if you haven't written the verb for this disc yet,
   # the .iso won't be moved to the right directory.  
   # So when writing a new verb, first run 'sh wisotool load',
   # then write just the verblist_add part (including sha1sum), then
   # run 'sh wisotool migrate' to move the iso into the right directory,
   # and then write the rest of the verb.
   migrate_files

   eject $ISO_MOUNT_ROOT || true    # punt if eject not found (as on cygwin)
}

#----------------------------------------------------------------

ahk_do() {
   echo "$@" | sed "s/\$//" > "$WISOTOOL_TMP"/tmp.ahk
   $WINE "$programfilesdir_unix/AutoHotkey/AutoHotkey.exe" "$WISOTOOL_TMP_WIN"\\tmp.ahk
}

#----------------------------------------------------------------

load_autohotkey()
{
    test -f "$programfilesdir_unix/AutoHotkey/AutoHotkey.exe" || try sh "$WINETRICKS" -q autohotkey
}

#----------------------------------------------------------------

verblist_init()
{
    # Must call this before first call to verblist_add
    file_map="case \"\$1\" in "
    # Clear menu
    rm -f "$WISOTOOL_TMP"/menutext
}

verblist_finish()
{
    # Must follow last call to verblist_add
    file_map="$file_map esac"
}

# Add a verb's description to the menu
menu_add() {
    verbname=$1
    description="$2"
    printf " %-24s %s\n" $verbname "$description" >> "$WISOTOOL_TMP"/menutext
}

# Add a new verb
verblist_add()
{
    # Usage: verblist_add verbname "description" file1 file2 ...
    verbname=$1
    description="$2"
    case "$description" in
    *\'*) die "bug in call to verblist_add($verbname $description): you can't use apostrophes in game descriptions, it breaks the zenity menu.  Please remove." ;;
    esac
    shift
    shift
    present=''
    test $verbname != 'help' && present=' [loaded]'
    for file
    do
       file_map="$file_map \"$file\") echo $verbname;; "
       if ! test -f "$WISOTOOL_CACHE/$verbname/$file"
       then
           present=''
       fi
    done
    menu_add $verbname "$description$present"
}

# Returns true if given verb is in the list
verblist_is_legal_verb()
{
  verb=$1
  awk '{print $1}' < "$WISOTOOL_TMP"/menutext > "$WISOTOOL_TMP"/verbs
  if grep "^$verb$" "$WISOTOOL_TMP"/verbs > /dev/null
  then
      return 0
  else
      return 1
  fi
}

# Given a file, output the verb it belongs to
map_file_to_verb()
{
   eval $file_map
}

# Output a list of the verbs for which the needed files are in the cache
list_available_verbs()
{
    # Find files in cache, output pathnames without top level directory.
    # Use "while read" rather than "for", since we have some filenames with spaces.
    (cd "$WISOTOOL_CACHE"; find . -type f) | sed 's,^./[^/]*/,,' | while read file
    do
        map_file_to_verb "$file"
    done | sort -u
}

# Move any/all *.iso or *.exe still at top level into the proper subdirectory
migrate_files()
{
    for file in "$WISOTOOL_CACHE"/*.iso "$WISOTOOL_CACHE"/*.exe
    do
        barefile=`basename $file`
        verb=`map_file_to_verb $barefile`
        if test "$verb" != ""
        then
            mkdir -p "$WISOTOOL_CACHE"/$verb
            movee=`echo $file | sed 's,\(\.iso\)$\|\(\.exe\)$,.*,g'`
            echo Moving $movee to $WISOTOOL_CACHE/$verb/
            mv $movee "$WISOTOOL_CACHE"/$verb/
        fi
    done
}

#----- Verbs ----------------------------------------------------

verblist_init

#----------------------------------------------------------------

verblist_add 3dmark2000 "3DMark2000 (MadOnion.com, 2000) [download]" 3dmark2000_v11_100308.exe

load_3dmark2000() {
    load_autohotkey

    # http://www.futuremark.com/download/3dmark2000/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3dmark2000_v11_100308.exe"
    then
        download $PACKAGE http://www.ocinside.de/download/3dmark2000_v11_100308.exe b0400d59cfd45d8c8893d3d4edc58b6285ee1502
    fi

    cd "$WISOTOOL_TMP"
    mkdir $PACKAGE
    cd $PACKAGE
    try unzip "$WISOTOOL_CACHE/$PACKAGE"/3dmark2000_v11_100308.exe
    ahk_do "
        SetTitleMatchMode, 2
        run Setup.exe
        WinWait Welcome
        ControlClick Button1  ; Next
        WinWait License
        ControlClick Button2  ; Yes
        ;WinWaitClose ahk_class #32770 ; License
        WinWait ahk_class #32770, Destination
        ControlClick Button1  ; Next
        ;WinWaitClose ahk_class #32770 ; Destination
        WinWait, Start
        ControlClick Button1  ; Next
        WinWait Registration
        ControlClick Button1  ; Next
        WinWait Complete
        ControlClick Button1  ; Unclick View Readme
        ControlClick Button4  ; Finish
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\MadOnion.com\3DMark2000"
REM possible wine cmd bug: "3dmark2000" aborts, but ".\3dmark2000" works
.\3DMark2000
__EOF__

}

#----------------------------------------------------------------

verblist_add 3dmark2001 "3DMark2001 (MadOnion.com, 2001) [download]" 3dmark2001se_330_100308.exe

load_3dmark2001() {
    load_autohotkey

    # http://www.futuremark.com/download/3dmark2001/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE"/3dmark2001se_330_100308.exe
    then
        download $PACKAGE http://www.ocinside.de/download/3dmark2001se_330_100308.exe 643bacbcc1615bb4f46d3b045b1b8d78371a6b54
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run 3dmark2001se_330_100308.exe
        WinWait ahk_class #32770 ; welcome
        ControlClick Button2  ; Next
        sleep 5000
        WinWait ahk_class #32770 ; License
        ControlClick Button2  ; Next
        WinWait ahk_class #32770, Destination
        ControlClick Button1  ; Next
        WinWait ahk_class #32770, Start
        ControlClick Button1  ; Next
        WinWait,, Registration
        ControlClick Button2  ; Next
        WinWait,, Complete
        ControlClick Button1  ; Unclick View Readme
        ControlClick Button4  ; Finish
    "
}

#----------------------------------------------------------------

verblist_add 3dmark03 "3D Mark 03 (Futuremark, 2003) [download]" 3DMark03_v360_1901.exe

load_3dmark03() {
    load_autohotkey

    # http://www.futuremark.com/benchmarks/3dmark03/download/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3DMark03_v360_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/3DMark03_v360_1901.exe 46a439101ddbbe3c9563b5e9651cb61b46ce0619
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    warn "Don't use mouse while this installer is running.  Sorry..."
    # This old installer doesn't seem to be scriptable the usual way, so spray and pray.
    ahk_do "
        run 3DMark03_v360_1901.exe
        Sleep 4000
        ; Welcome
        Send {Enter}
        Sleep 2000
        ; Accept license
        Send a
        Send {Enter}
        Sleep 2000
        ; Choose Destination
        Send {Enter}
        Sleep 2000
        ; Begin install
        Send {Enter}
        ; Wait for install to finish
        Sleep 35000
        ; Purchase later
        Send {Tab}
        Send {Tab}
        Send {Enter}
        ; Uncheck readme
        Send {Space}
        Send {Tab}
        Send {Tab}
        Send {Enter}
    "
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\3DMark03"
3DMark03
__EOF__
}

#----------------------------------------------------------------

verblist_add 3dmark05 "3D Mark 05 (Futuremark, 2005) [download]" 3DMark05_v130_1901.exe

load_3dmark05() {
    load_autohotkey

    # http://www.futuremark.com/download/3dmark05/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3DMark05_v130_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/3DMark05_v130_1901.exe 8ad6bc2917e22edf5fc95d1fa96cc82515093fb2
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run 3DMark05_v130_1901.exe
        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        ControlClick Button1 ; Accept
        ControlClick Button4 ; Next
        WinWait, ahk_class #32770, Destination
        ControlClick Button1 ; Next
        WinWait, ahk_class #32770, Install
        ControlClick Button1 ; Install
        WinWait, ahk_class #32770, Purchase
        ControlClick Button4 ; Later
        WinWait, ahk_class #32770, Complete
        ControlClick Button1 ; Uncheck view readme
        ControlClick Button3 ; Finish
    "
    ARGS=""
    if workaround_wine_bug 22392
    then
        warn "You must run the app with the -nosysteminfo option to avoid a crash on startup"
        ARGS="-nosysteminfo"
    fi
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\3DMark05"
3DMark05 $ARGS
__EOF__
}

#----------------------------------------------------------------

verblist_add 3dmark06 "3D Mark 06 (Futuremark, 2006) [download]" 3DMark06_v120_1901.exe

load_3dmark06() {
    load_autohotkey

    # http://www.futuremark.com/benchmarks/3dmark06/download/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/3DMark06_v120_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/3DMark06_v120_1901.exe 2e4a52d5b0f7caebd7b4407dfa9e258ac623b5dd
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run 3DMark06_v120_1901.exe
        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        ControlClick Button1 ; Accept
        ControlClick Button4 ; Next
        WinWait, ahk_class #32770, Destination
        ControlClick Button1 ; Next
        WinWait, ahk_class #32770, Install
        ControlClick Button1 ; Install
        WinWait ahk_class OpenAL Installer
        ControlClick Button2 ; OK
        WinWait ahk_class #32770
        ControlClick Button1 ; OK
        WinWait, ahk_class #32770, Purchase
        ControlClick Button4 ; Later
        WinWait, ahk_class #32770, Complete
        ControlClick Button1 ; Uncheck view readme
        ControlClick Button3 ; Finish
        WinWaitClose, ahk_class #32770, Complete
    "

    if workaround_wine_bug 9210
    then
        warn "You may need to apply the patch in http://bugs.winehq.org/show_bug.cgi?id=9210 to fix pCaps->MaxPointSize, or the benchmark will warn that shader model 2.0 is not present, and refuse to run."
    fi

    if workaround_wine_bug 22393
    then
        # "Demo" button doesn't work without this
        sh "$WINETRICKS" -q d3dx9_28 d3dx9_36
    fi

    ARGS=""
    if workaround_wine_bug 22392
    then
        warn "You must run the app with the -nosysteminfo option to avoid a crash on startup"
        ARGS="-nosysteminfo"
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\3DMark06"
3DMark06 $ARGS
__EOF__
}

#----------------------------------------------------------------

verblist_add assassinscreed "Assassins Creed (Ubisoft, 2008)" a62112860423b32bf3ea77df6f5fe0b60c772de2.iso

load_assassinscreed() {
    load_autohotkey

    if workaround_wine_bug 22392
    then
        # Don't hang at a dialog box when Detection crashes
        sh "$WINETRICKS" nocrashdialog
    fi

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/a62112860423b32bf3ea77df6f5fe0b60c772de2.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        SetTitleMatchMode, 2
        winwait, InstallShield Wizard, Language
        ; wine bug? - clicking on Next does nothing until you move the mouse over the installer window
        ;ControlClick Next, InstallShield Wizard
        Send {Enter}
        winwait, InstallShield Wizard, Welcome
        ControlClick Next, InstallShield Wizard
        winwait, InstallShield Wizard, License
        sleep 500
        send a{Enter}
        winwait, InstallShield Wizard, begin
        sleep 1000
        ControlClick &Install, InstallShield Wizard
        winwait, Product Registration, register
        ControlClick Never, Product Registration
        ControlClick Button1, Product Registration
        winwait, InstallShield Wizard, inish
        send {Enter}
    "
    iso_umount

    # Should run AssassinsCreed_Launcher.exe, but that fails on Wine
    # Should give option to run AssassinsCreed_Dx10.exe, but that fails on Wine
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Ubisoft\Assassin's Creed"
AssassinsCreed_Dx9.exe
__EOF__
}

#----------------------------------------------------------------

# http://appdb.winehq.org/objectManager.php?sClass=version&iId=408
verblist_add baldursgate2       "Baldurs Gate 2 - Shadows of Amn (Bioware, 2000)" \
  cc9359dce1a7be6c64bb6f8e6dea6d14d4a5f716.iso \
  429872605dad10433c3c581a1c11eba4d0988c46.iso \
  a6d18fcd7d16ddafbda7aa028b117566b1e09d2a.iso \
  94ed41768949c89a1a6479305f00a9cee1d2dcd5.iso

load_baldursgate2() {
    load_autohotkey

    # Possible wine bug: cd is still in use, even if wine eject is used. Workaround it by
    # copying all the cd's to a directory, and running the installer from there.
    # You still need the first CD mounted at the end, however...
    if test ! -d "$WISOTOOL_TMP"/$PACKAGE/tempcd
    then
        try mkdir -p "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/cc9359dce1a7be6c64bb6f8e6dea6d14d4a5f716.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/429872605dad10433c3c581a1c11eba4d0988c46.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/a6d18fcd7d16ddafbda7aa028b117566b1e09d2a.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/94ed41768949c89a1a6479305f00a9cee1d2dcd5.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_TMP"/$PACKAGE/tempcd
    fi
    
    # Will perform a full install, so no cd's needed
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/cc9359dce1a7be6c64bb6f8e6dea6d14d4a5f716.iso
    
    ahk_do "
        SetTitleMatchMode, 2
        run "$WISOTOOL_TMP"/$PACKAGE/tempcd/setup.exe
        winwait, Baldur's Gate, Welcome to the Baldur's Gate
        sleep 1000
        ControlClick, Button1, Baldur's Gate, Welcome to the Baldur's Gate
        winwait, Baldur's Gate, Please read the following License Agreement
        sleep 1000
        ControlClick, Button2, Baldur's Gate, Please read the following License Agreement
        winwait, Baldur's Gate, Setup will install Baldur's Gate
        sleep 1000
        ControlClick, Button1, Baldur's Gate, Setup will install Baldur's Gate
        winwait, Baldur's Gate, Click the type of Setup you prefer
        sleep 1000
        ControlClick, Listbox1, Baldur's Gate, Click the type of Setup you prefer
        send {F}
        ControlClick, Button2, Baldur's Gate, Click the type of Setup you prefer
        winwait, Baldur's Gate, Setup will add program icons
        sleep 1000
        ControlClick, Button2, Baldur's Gate, Setup will add program icons
        winwait, Setup Needs The Next Disk
        sleep 1000
        Send {Home}
        Send {Shift down}
        Send {End}
        Send I:{Enter}
        winwait, Information
        sleep 1000
        ControlClick, Button1, Information
        Sleep 5000
        process, wait, Promo.exe, 5
        promopid = %ErrorLevel%
        winclose, ahk_pid %promopid%
        winwait, Baldur's Gate, Setup has finished installing
        sleep 1000
        ControlClick, Button4, Baldur's Gate, Setup has finished installing
        "
    try chmod +w -R "$WISOTOOL_TMP"/$PACKAGE/tempcd
    try rm -rf "$WISOTOOL_TMP"/$PACKAGE/tempcd

    # Install latest patch
    download baldursgate2 http://downloads.bioware.com/baldursgate2/Baldur%27sGateII-ShadowsofAmnPatchENGLISH.exe 4706c0dc1e282bae14946c87a38e2781f89ebdc4
    # AHK doesn't like its name...
    try cp -f "$WISOTOOL_CACHE/baldursgate2/Baldur%27sGateII-ShadowsofAmnPatchENGLISH.exe" "$WISOTOOL_TMP/baldurs_gate_2_patch.exe"

    cd "$WISOTOOL_TMP"
    ahk_do "
        SetTitleMatchMode, 2
        run, baldurs_gate_2_patch.exe
        winwait InstallShield Wizard, Welcome to the InstallShield Wizard
        sleep 1000
        ControlClick Button1, InstallShield Wizard, Welcome to the InstallShield Wizard
        winwait InstallShield Wizard, InstallShield Wizard Complete
        sleep 1000
        ControlClick Button4, InstallShield Wizard, InstallShield Wizard Complete
        exit"
    cd -
    try rm "$WISOTOOL_TMP/baldurs_gate_2_patch.exe"
    
    if workaround_wine_bug 22482
    then
        sh "$WINETRICKS" -q ddr=opengl
        warn "Enabling 3d acceleration in BGConfig.exe will improve performance."
    fi
    
    if workaround_wine_bug 22493
    then
        warn "Enabling 3d acceleration in BGConfig.exe will improve performance."
    fi

    if test ! "$WINE" = ""
    then
        warn "Until wine bug 22511 is fixed, you should use a virtual desktop, or baldur's gate will only take up part of your screen in full screen mode."
    fi
}

#----------------------------------------------------------------

verblist_add bfbc2       "Battlefield Bad Company 2 (EA, 2010)" \
  9ec587f1eda0f8bf13f485526e3c46e4f9d477a6.iso

load_bfbc2() {
    load_autohotkey
    exedir="$programfilesdir_x86_unix/Electronic Arts/Battlefield Bad Company 2"

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/9ec587f1eda0f8bf13f485526e3c46e4f9d477a6.iso
    BFBC2_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/9ec587f1eda0f8bf13f485526e3c46e4f9d477a6.txt | tr -d -`
    ahk_do "
        SetTitleMatchMode, 2
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, Bad Company, English
        ControlClick, Next, Bad Company
        winwait, Bad Company, Registration Code
        send {RAW}$BFBC2_KEY
        ControlClick, Next, Bad Company, Registration Code
        winwait, Bad Company, Setup Wizard will install
        ControlClick, Button1, Bad Company, Setup Wizard
        winwait, Bad Company, License Agreement
        ControlClick, Button1, Bad Company, License Agreement
        ControlClick, Button3, Bad Company, License Agreement
        winwait, Bad Company, End-User License Agreement
        ControlClick, Button1, Bad Company, License Agreement
        ControlClick, Button3, Bad Company, License Agreement
        winwait, Bad Company, Destination Folder
        ControlClick, Button1, Bad Company, Destination Folder
        winwait, Bad Company, Ready to install
        ControlClick, Install, Bad Company, Ready to install
        winwait, Authenticate Battlefield
        ControlClick, Disc authentication, Authenticate Battlefield
        ControlClick, Button4, Authenticate Battlefield
        winwait, Bad Company, PunkBuster
        ControlClick, Button4, Bad Company, PunkBuster
        ControlClick, Finish, Bad Company
    "
    iso_umount

    warn "Patching to latest version..."
    cd "$exedir"
    ahk_do "
        SetTitleMatchMode, 2
        run, BFBC2Updater.exe
        winwait, Updater, have to update to
        ControlClick, Yes, Updater, have to update
        winwait, Updater, successfully updated
        ControlClick,No, Updater, successfully updated
    "

    if workaround_wine_bug 22762
    then
        cd "$DRIVE_C/users/$USERNAME/My Documents"
        if test -f BFBC2/settings.ini
        then
            mv BFBC2/settings.ini BFBC2/oldsettings.ini
            sed 's,DxVersion=auto,DxVersion=9,;
                 s,Fullscreen=true,Fullscreen=false,' BFBC2/oldsettings.ini > BFBC2/settings.ini 
        else
            mkdir -p BFBC2
            echo "[Graphics]" > BFBC2/settings.ini
            echo "DxVersion=9" >> BFBC2/settings.ini
        fi
    fi
    cd "$olddir"
    
    if workaround_wine_bug 22961
    then
        warn "If you get a Securom 'No CD/DVD error', check your mount settings. See http://bugs.winehq.org/show_bug.cgi?id=22961 for more info."
    fi
}

#----------------------------------------------------------------

# http://appdb.winehq.org/objectManager.php?sClass=version&iId=9320
# Fails to install with an iso, need to use an mdf/mds from Alcohol 120% on Windows
# FIXME: mds/mdf files have different sha1sum's, and depending on the rip settings, the mds might as well?
# Sha1sum's:
# plain iso, from dd: deaf00ebee6e73aecf38f704c3f516008a68d888
# mds: 391042ea19b4eace5d532dbade10931ebbc4def6
# mdf: deaf00ebee6e73aecf38f704c3f516008a68d888
verblist_add bioshock       "Bioshock (2K Games, 2007)" \
  391042ea19b4eace5d532dbade10931ebbc4def6.mds

load_bioshock() {
    load_autohotkey
    
    # Bioshock needs MSVCP80.dll to run, which Wine doesn't have yet.
    if workaround_wine_bug 22501
    then
        sh "$WINETRICKS" -q vcrun2005
    fi
    
    # Will perform a full install, so no cd's needed
    mds_mount "$WISOTOOL_CACHE/$PACKAGE/391042ea19b4eace5d532dbade10931ebbc4def6.mds"

    # Setup cdemu for Bioshock (dpm on, tr off):
    # FIXME: I'm assuming different programs may want different emulation settings. If not, move up to mds_mount().
    cdemu dpm-emulation 0 1
    cdemu tr-emulation 0 0

    # Don't trim the hyphen's "-", the installer won't proceed without them.
    BIOSHOCK_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/391042ea19b4eace5d532dbade10931ebbc4def6.txt`
    
    ahk_do "
        SetTitleMatchMode, 2
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, BioShock - InstallShield Wizard, Choose Setup Language
        sleep 2000
        ControlClick, Button3, BioShock - InstallShield Wizard, Choose Setup Language
        ControlClick, Button3, BioShock - InstallShield Wizard, Choose Setup Language ; Installer seems fidgety
        winwait, BioShock - InstallShield Wizard, Welcome to the InstallShield Wizard for BioShock
        sleep 1000
        ControlClick, Button1, BioShock - InstallShield Wizard, Welcome to the InstallShield Wizard for BioShock
        winwait, BioShock - InstallShield Wizard, Please read the following license agreement carefully
        sleep 1000
        ControlClick, Button5, BioShock - InstallShield Wizard, Please read the following license agreement carefully
        sleep 1000
        ControlClick, Button2, BioShock - InstallShield Wizard, Please read the following license agreement carefully
        winwait, BioShock - InstallShield Wizard, Select the setup type to install
        sleep 1000
        ControlClick, Button2, BioShock - InstallShield Wizard, Select the setup type to install
        winwait, BioShock - InstallShield Wizard, Click Install to begin the installation
        ControlClick, Button1, BioShock - InstallShield Wizard, Click Install to begin the installation
        winwait, BioShock - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
        sleep 1000
        ControlClick, Button6, BioShock - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
        sleep 1000
        ControlClick, Button4, BioShock - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
        winwait, Welcome, &Next
        Sleep 1000
        ControlClick, Button2, Welcome, &Next
        winwait, Enter your serial number, &Activate
        Sleep 1000
        ControlClick, Edit1, Enter your serial number, &Activate
        send {Raw}$BIOSHOCK_KEY
        Sleep 1000
        ControlClick, Button1, Enter your serial number, &Activate
        winwait, Activation Successful
        Sleep 1000
        Controlclick, Button3, Activation Successful
        "
    # According to the AppDB, 1.1 may have problems with Wine. For now, don't run it.
    # FIXME: Test and if there's a Wine bug, file one/put this in an if workaround_wine_bug().
    #
    #download $PACKAGE http://downloads.2kgames.com/bioshock/patch/Bioshock_Version_11_Patch_Worldwide_Retail.zip
    #cd $WISOTOOL_TMP
    #unzip "$WISOTOOL_CACHE/$PACKAGE/Bioshock_Version_11_Patch_Worldwide_Retail.zip"
    #ahk_do "
    #    run Bioshock Version 1.1 Patch Worldwide Retail.exe
    #    winwait, BioShock 1.1 Patch, This patch is to be applied ONLY to the Uncensored Retail Version of BioShock
    #    sleep 1000
    #    ControlClick, Button1, BioShock 1.1 Patch, This patch is to be applied ONLY to the Uncensored Retail Version of BioShock
    #    winwait, Location Confirmation, Is located at
    #    sleep 1000
    #    ControlClick, Button1, Location Confirmation, Is located at
    #    winwait, License Agreement, Please read the following license agreement carefully.
    #    sleep 1000
    #    ControlClick, Button1, License Agreement, Please read the following license agreement carefully.
    #    winwait, BioShock Patched Successfully!, BioShock patched to version 1.1 successfully!
    #    sleep 1000
    #    ControlClick, Button1, BioShock Patched Successfully!, BioShock patched to version 1.1 successfully!
    #    "
    if workaround_wine_bug 6971
    then
        sh "$WINETRICKS" -q mwo=force
    fi

    mds_umount
}

#----------------------------------------------------------------

verblist_add bioshock_demo       "Bioshock Demo (2K Games, 2007)" \
  nzd_BioShockPC.zip

load_bioshock_demo() {
    load_autohotkey
    download $PACKAGE http://us.download.nvidia.com/downloads/nZone/demos/nzd_BioShockPC.zip 7a19186602cec5210e4505b58965e8c04945b3cf
    cd "$DRIVE_C"
    rm -rf bioshock-temp
    mkdir bioshock-temp
    cd bioshock-temp
    try unzip -q "$WISOTOOL_CACHE/$PACKAGE"/nzd_BioShockPC.zip
    try cd "BioShock PC Demo"
    ahk_do "
        SetTitleMatchMode, 2
        run setup.exe
        winwait, BioShock Demo - InstallShield Wizard, Choose Setup Language
        sleep 2000
        ControlClick, Button3
        ControlClick, Button3
        winwait, BioShock Demo - InstallShield Wizard, Welcome
        sleep 1000
        ControlClick, Button1
        winwait, BioShock Demo - InstallShield Wizard, Please read
        sleep 1000
        ControlClick, Button5
        sleep 1000
        ControlClick, Button2
        winwait, BioShock Demo - InstallShield Wizard, Select the setup type
        sleep 1000
        ControlClick, Button2
        winwait, BioShock Demo - InstallShield Wizard, Click Install to begin
        ControlClick, Button1
        winwait, BioShock Demo - InstallShield Wizard, The InstallShield Wizard has successfully installed BioShock
        sleep 1000
        ControlClick, Button2     ; don't launch
        ControlClick, Button6     ; don't show readme
        send {Enter}              ; finish
    "
    cd ..
    rm -rf bioshock-temp
    cd "$olddir"
}

#----------------------------------------------------------------

verblist_add blur       "Blur (Activision, 2010)" \
  30fdaf3aad82be846f26b7908c703598d5c3443d.iso

load_blur() {
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/30fdaf3aad82be846f26b7908c703598d5c3443d.iso

    ahk_do "
        Run, ${ISO_MOUNT_LETTER}:Setup.exe
        SetTitleMatchMode, 2
        winwait, Activision, Select the language
        send {Enter}
        winwait, Blur, install Blur
        send {Enter}
        winwait, Blur, License
        ControlClick Button5
        send {Enter}
        winwait, Blur, Minimum System
        send {Enter}
        winwait, Blur, Setup Type
        send {Enter}
        ; Installer seems to crash at end on Win7 and Wine
        ; FIXME: loop waiting for some other event ("Finalizing installation"?)
        winwait, Blur, Finish
        send {Enter}
    "
    iso_umount
}

#----------------------------------------------------------------

verblist_add codmw2        "Call of Duty Modern Warfare 2 (Activision, 2009) [broken]" \
  6f572261ed954733806daf5b42edf92b3127cd14.iso \
  3c6e63504d41df4bdb2d4c57f4c5fc7b810d7df8.iso

load_codmw2()
{
    warn "This verb isn't quite ready for prime time."
    load_autohotkey
    test -f "$programfilesdir_x86_unix"/Steam/Steam.exe || sh $WINETRICKS -q steam

    # Get user's key
    CODMW2_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/6f572261ed954733806daf5b42edf92b3127cd14.txt | tr -d -`

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/6f572261ed954733806daf5b42edf92b3127cd14.iso
    cd "$programfilesdir_x86_unix"/Steam
    ahk_do "
        SetTitleMatchMode, 2
        Run, Steam.exe -login $STEAMUSER $STEAMPW -install ${ISO_MOUNT_LETTER}:

	; Uncomment these lines if you haven't activated this game via steam on this account before.
        ;winwait, Activation
        ;MouseMove, 30, 400
        ;Click
        ;Sleep 300
        ;send {Raw}$CODMW2_KEY
        ;MouseMove, 306, 566
        ;Click
        ;winwait, Activation
        ;sleep 10000
        ;MouseMove, 310, 565
        ;Click

        winwait, Install
        sendEvent {Enter}
        ; wait for "create start menu and install" question
        sleep 5000
        sendEvent {Enter}
        winwait, Insert
    "
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/3c6e63504d41df4bdb2d4c57f4c5fc7b810d7df8.iso
    ahk_do "
        SetTitleMatchMode, 2
        Send {Enter}
	; Need to wait for install to finish.  This isn't the way to do it.  Ideally we could watch some log file.
	; The last file created seems to be
	; "Program Files/Steam/steamapps/call of duty modern warfare 2 content.ncf"
	; so wait for that and then another 20 seconds, say.
        winwait, ahk_class USurface_, Install
	; Now that install has finished, say "don't start app" and "finish".
        Send {Space}
        Send {Enter}
	; Now wait for the main steam interface to pop up, and close it
        winwait, ahk_class USurface_, Steam
        WinClose

	; If you choose to start the game above, you could wait for it to be ready to play here.  
        ;winwait, ahk_class USurface_8390, Ready
        ;Send {Tab}            # select Close
        ;Send {Enter}
	;winwait, Steam Login
        ;WinClose
    "
    iso_umount
    
}

#----------------------------------------------------------------

verblist_add diablo2       "Diablo II (Blizzard, 2000)" \
  e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso \
  51e2c630d5dd017e6168a8cf3ee24e39010316d9.iso \
  382ea98f270e39855b558b8fac0d609712a54ae8.iso \
  e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso

load_diablo2() {
    warn "You must have already done 'wisotool load=YOURKEY' on the install disc, and 'wisotool load' on the other two discs." 
    load_autohotkey
    download diablo2 http://ftp.blizzard.com/pub/diablo2/patches/PC/D2Patch_113c.exe c78761bfb06999a9788f25a23a1ed30260ffb8ab

    # Force clean-ish install
    test -d "$programfilesdir_unix/Diablo II" && rm -rf "$programfilesdir_unix/Diablo II"

    # Get user's key
    DIABLOIIKEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/e20efb1ea60e58b4a25275a00571aabfe3ab4511.txt | tr -d -`

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, Diablo II Setup
        send {i}
        winwait, Choose Installation Size
        send {u}
        send {Enter}
        send {Raw}$USERNAME
        send {Tab}{Raw}$DIABLOIIKEY
        send {Enter}
        winwait, Diablo II - choose install directory
        send {Enter}
        winwait, Desktop Shortcut
        send {N}
        winwait, Insert Disc"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/51e2c630d5dd017e6168a8cf3ee24e39010316d9.iso
    # Needed by patch 1.13c to avoid disc swapping
    cp "$ISO_MOUNT_ROOT"/d2music.mpq "$programfilesdir_unix/Diablo II/"
    ahk_do "
        send, {Enter}
        Sleep 1000
        winwait, Insert Disc"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/382ea98f270e39855b558b8fac0d609712a54ae8.iso
    ahk_do "
        send, {Enter}
        Sleep 1000
        winwait, Insert Disc"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/e20efb1ea60e58b4a25275a00571aabfe3ab4511.iso
    ahk_do "
        send, {Enter}
        Sleep 1000
        winwait, View ReadMe?
        ControlClick &No, View ReadMe?
        winwait, Register Diablo II Electronically?
        send {N}
        winwait, Diablo II Setup - Video Test
        ControlClick &Cancel, Diablo II Setup - Video Test
        winclose, Diablo II Setup"
    iso_umount

    try "$WINE" "$WISOTOOL_CACHE"/diablo2/D2Patch_113c.exe
    ahk_do "
        winwait Blizzard Updater v2.72
        send {Enter}
        winwait Diablo II
        ControlClick &Cancel, Diablo II"
    # Dagnabbit, the darn updater starts the game after it updates, no matter what I do?
    killall "Game.exe"

    warn "When starting the game, be patient, wait until the menu appears.  The game seems to hang if it looses focus, see bug 14456, you may need to set winecfg to virtual desktop."

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Diablo II"
"Diablo II.exe"
__EOF__
}

#----------------------------------------------------------------

verblist_add dragonage     "Dragon Age: Origins (Bioware, 2009)" 705a6b06d0dd807bf62b4391d278649d728ebda4.iso

load_dragonage() {
    warn "You must have already done 'wisotool load=YOURKEY' on the install disc." 
    load_autohotkey

    # Get user's key
    DRAGONAGEKEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/705a6b06d0dd807bf62b4391d278649d728ebda4.txt | tr -d -`

    # Installer has a non-fatal crash on exit, so ignore it.
    sh "$WINETRICKS" -q nocrashdialog physx vcrun2005
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/705a6b06d0dd807bf62b4391d278649d728ebda4.iso

    ahk_do "
        Run, ${ISO_MOUNT_LETTER}:Setup.exe
        SetTitleMatchMode, 2
        winwait, Installer Language
        send {Enter}
        winwait, Dragon Age: Origins Setup
        ControlClick Next, Dragon Age: Origins Setup
        winwait, Dragon Age: Origins Setup, End User License
        ControlClick Button4, Dragon Age: Origins Setup
        ControlClick I agree, Dragon Age: Origins Setup
        SetTitleMatchMode, 1
        winwait, Dragon Age: Origins, Registration
        send $DRAGONAGEKEY
        send {Enter}
        winwait, Dragon Age: Origins Setup, Install Type
        Sleep 1000
        send {Enter}
        loop 100
        {
            IfWinExist, Dragon Age: Origins Setup
                sleep 60000
        }
        exit 0
    "
    iso_umount
    
    if workaround_wine_bug 22383
    then
        try "$WINETRICKS" -q strictdrawordering=enabled
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Dragon Age"
bin_ship\daorigins.exe
__EOF__
}

#----------------------------------------------------------------
 
verblist_add gta_vc     "Grand Theft Auto: Vice City (Rockstar, 2003) " \
  e98c2d323dd0494989a844442586dc2d48fba8f9.iso \
  d31f5c35cc63d804a7ffdb212f550681b97ee5b3.iso

load_gta_vc() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/e98c2d323dd0494989a844442586dc2d48fba8f9.iso
    ahk_do "
    SetTitleMatchMode, 2
    Run, ${ISO_MOUNT_LETTER}:Setup.exe
    winwait, Choose Setup Language
    sleep 1000
    Send {enter}
    winwait, Grand Theft Auto Vice City, Welcome to the InstallShield Wizard
    sleep 1000
    Send {enter}
    winwait, Grand Theft Auto Vice City, License Agreement
    sleep 1000
    Send !a
    send {enter}
    winwait, Grand Theft Auto Vice City, Customer Information
    sleep 1000
    controlclick, edit1
    send $USERNAME
    send {tab}
    send company ; installer won't proceed without something here
    send {enter}
    winwait, Grand Theft Auto Vice City, Choose Destination Location
    sleep 1000
    controlclick, Button1
    winwait, Grand Theft Auto Vice City, Select Components
    sleep 1000
    controlclick, Button2
    winwait, Grand Theft Auto Vice City, Ready to Install the Program
    sleep 1000
    send {enter}
    winwait, Setup Needs The Next Disk, Please insert disk 2
    sleep 1000"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/d31f5c35cc63d804a7ffdb212f550681b97ee5b3.iso
    ahk_do "
    sleep 1000
    send {enter}
    winwait, Grand Theft Auto Vice City, InstallShield Wizard Complete
    sleep 1000
    send {enter}
    "
    iso_umount
    
    if workaround_wine_bug 22414
    then
        try "$WINETRICKS" -q quartz
    fi
}

#----------------------------------------------------------------
 
verblist_add half_life_goty     "Half Life: Game of the Year Edition (Sierra, 2000) " \
  dc32c16bca6c19f14e3501e3be3e4a157ddbee20.iso

load_half_life_goty() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/dc32c16bca6c19f14e3501e3be3e4a157ddbee20.iso
    
    ahk_do "
    SetTitleMatchMode, 2
    Run, ${ISO_MOUNT_LETTER}:Setup.exe
    winwait, System Test, Did you hear the sound file?
    sleep 1000
    ControlClick, Button6, System Test, Did you hear the sound file?
    winwait, Welcome, Welcome to the Half-Life Setup program.  This program will install Half-Life on your computer.
    sleep 1000
    ControlClick, Button1, Welcome, Welcome to the Half-Life Setup program.  This program will install Half-Life on your computer.
    winwait, Software License Agreement, Please read the following License Agreement.  Press the PAGE DOWN key to see the rest of the agreement.
    sleep 1000
    ControlClick, Button2, Software License Agreement, Please read the following License Agreement.  Press the PAGE DOWN key to see the rest of the agreement.
    winwait, Choose Destination Location, Setup will install Half-Life in the following folder.
    sleep 1000
    ControlClick, Button1, Choose Destination Location, Setup will install Half-Life in the following folder.
    winwait, Install, Setup has placed the Sierra Utilities in your Start Menu.
    sleep 1000
    ControlClick, Button1, Install, Setup has placed the Sierra Utilities in your Start Menu.
    winwait, Install, Setup has determined that there may be updates to your product available.
    sleep 1000
    ControlClick, Button7, Install, Setup has determined that there may be updates to your product available.
    winwait, Install, Please Register Now!
    sleep 1000
    ControlClick, Button1, Install, Please Register Now!
    winwait, Choose Method of Registration, Please choose a registration method
    sleep 1000
    ControlClick, Button8, Choose Method of Registration, Please choose a registration method
    winwait, Select Components, Please ensure you are running the latest drivers appropriate for your hardware
    sleep 1000
    ControlClick, Button11, Select Components, Please ensure you are running the latest drivers appropriate for your hardware
    winwait, Setup Complete, Setup has finished installing Half-Life on your computer.
    sleep 1000
    ControlClick, Button1, Setup Complete, Setup has finished installing Half-Life on your computer.
    Sleep 1000
    ControlClick, Button4, Setup Complete, Setup has finished installing Half-Life on your computer.
    "
    
    # The key is put in on first run:
    HALF_LIFE_GOTY_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/dc32c16bca6c19f14e3501e3be3e4a157ddbee20.txt`
    cd $DRIVE_C/SIERRA/Half-Life
    
    # Forcefully closing the process later will screw up the screen resolution, so store the user's current resolution so we can restore it later:
    current_res=`xrandr -q | awk -F'current' -F',' 'NR==1 {gsub("( |current)","");print $2}'`

    # FIXME: Not sure how reliable the ahk_class designation is...
    ahk_do "
    Run, hl.exe
    winwait, ahk_class #32770
    sleep 1000
    ControlClick, Edit1, ahk_class #32770
    Send {RAW}$HALF_LIFE_GOTY_KEY
    sleep 1000
    ControlClick, Button1, ahk_class #32770
    sleep 5000
    ; I tried closing it the nice way, with either PostMessage or Win_close, but neither worked
    process, close, hl.exe
    "
    xrandr -s $current_res
}

#----------------------------------------------------------------

verblist_add help     "How to use this tool"

load_help() {
    warn "If the game is not marked with {download} or {loaded} in the menu, you have to insert its disc and give the 'load' command before you can choose that game in the menu.  If the game has multiple discs, you have to do this for each disc."
    warn "If the game has an install key, you have to enter that when loading the first disc.  (You have to do that from the commandline, e.g. sh wisotool load=XXXX-YYYY-ZZZZ.)"
}

#----------------------------------------------------------------

honexe=HoNClient-1.0.0.1.exe
verblist_add hon "Heroes of Newerth (S2 Games, 2010) [download]" \
$honexe

load_hon()
{
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/$honexe"
    then
        download $PACKAGE http://dl2.heroesofnewerth.com/$honexe
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, $honexe
        winwait, Heroes of Newerth
        controlclick, Button2, Heroes of Newerth
        winwait, Heroes of Newerth, License
        controlclick, Button2, Heroes of Newerth, License
        winwait, Heroes of Newerth, Components
        controlclick, Button2, Heroes of Newerth, Components
        winwait, Heroes of Newerth, Install Location
        controlclick, Button2, Heroes of Newerth, Install Location
        winwait, Heroes of Newerth, Start Menu
        controlclick, Button2, Heroes of Newerth, Start Menu
        winwait, Heroes of Newerth, Finish
        controlclick, Button2, Heroes of Newerth, Finish
    "
    cd "$olddir"

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Heroes of Newerth"
hon.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add lswcs "Lego Star Wars Complete Saga (Lucasarts, 2009)" dc5db10e2ad2892ba40015d3856d1d29dc55893a.iso

load_lswcs() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/dc5db10e2ad2892ba40015d3856d1d29dc55893a.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        SetTitleMatchMode, 2
        winwait, Choose Setup Language
        send {Enter}
        winwait, LEGO, License Agreement
	send a{Enter}
        winwait, LEGO, method
        ControlClick Easy Installation
        sleep 1000
        winwaitclose, LEGO
    "
    # Installer crashes at end (http://bugs.winehq.org/show_bug.cgi?id=22529) but this doesn't seem to hurt.
    # Wait for all processes to exit, else unmount will fail
    # FIXME: use right wineserver
    wineserver -w
    iso_umount

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\\LucasArts\\LEGO Star Wars - The Complete Saga"
LEGOStarWarsSaga.exe
__EOF__

    warn "This game is copy-protected, and requires the real disc in a real drive to run."
}

#----------------------------------------------------------------

# Note: may require load_harder.  Result may vary in length and checksum.

verblist_add manhole     "The Manhole Masterpiece Edition (Cyan, 1994)" \
  39aea1267c2b2b22a7d5c1e9f86ea1f4461457e3.iso

load_manhole() {
    cd $WISOTOOL_TMP

    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/39aea1267c2b2b22a7d5c1e9f86ea1f4461457e3.iso
    mkdir -p "$DRIVE_C"/manhole
    try cp -r "$ISO_MOUNT_ROOT"/* "$DRIVE_C"/manhole
    iso_umount

    if workaround_wine_bug 22502
    then
        warn "Run with wine-1.0 to avoid crash on startup.  Also cancel when prompted to install Quicktime."
    fi
}

#----------------------------------------------------------------

verblist_add masseffect2       "Mass Effect 2 (BioWare, 2010)" \
  4b817d67c8b7e8e7bc33f8cb6047210ab554fef6.iso \
  49d1f9b85203049d52a8e34b92cd7d4b96e0c8be.iso

load_masseffect2() {
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/4b817d67c8b7e8e7bc33f8cb6047210ab554fef6.iso
    ME2_KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/4b817d67c8b7e8e7bc33f8cb6047210ab554fef6.txt | tr -d -`

    if workaround_wine_bug 22091
    then
        warn "Will probably hang at end of installer.  If a crash dialog comes up, you can kill it, it's done."
        #try sh "$WINETRICKS" -q nocrashdialog
    fi

    ahk_do "
        SetTitleMatchMode, 2
        run, ${ISO_MOUNT_LETTER}:Setup.exe
        winwait, Installer Language
        send {Enter}
        winwait, Mass Effect
        ControlClick, Button2
        winwait, Mass Effect, License
        ControlClick, Button4
        ControlClick, Button2
        winwait, Mass Effect, Registration Code
        send {RAW}$ME2_KEY
        ControlClick, Button2
        winwait, Mass Effect, Install Type
        ControlClick, Button2
        winwait, Insert Disc
    "
    sleep 5
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/49d1f9b85203049d52a8e34b92cd7d4b96e0c8be.iso
    ahk_do "
        ControlClick, Button4, Insert Disc
        ; Some installs may not get to this point due to an installer hang/crash (bug 22091)
        ; The hang/crash happens after the Physx install but does not seem to affect gameplay
        winwait, Mass Effect, Finish
        winkill, Mass Effect
    "
    if workaround_wine_bug 6971
    then
        echo "See http://appdb.winehq.org/objectManager.php?sClass=version&iId=19125 for info on how to patch wine to work around bug 6971"
    fi
}

#----------------------------------------------------------------

verblist_add morrowind     "The Elder Scrolls III: Morrowind (Bethesda, 2002)" \
  c8368ed30d3f3fcd7fccf8bffcfcdf0a6d4cb68b.iso

load_morrowind() {
    cd $WISOTOOL_TMP
    # FIXME: Untested on Windows!

    # FIXME: Only supports the main installer, and the construction set (which follows automatically)
    # eventually should support the expansions as well
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/c8368ed30d3f3fcd7fccf8bffcfcdf0a6d4cb68b.iso
    ahk_do "
    SetTitleMatchMode, 2
    Run, ${ISO_MOUNT_LETTER}:Setup.exe
    winwait, The Elder Scrolls III:  Morrowind Setup, The Elder Scrolls III:  Morrowind (License Agreement)
    sleep 1000
    controlclick, Button2
    winwait, The Elder Scrolls III:  Morrowind Setup, Please read the following important information.
    sleep 1000
    controlclick, Button1
    winwait, The Elder Scrolls III:  Morrowind Setup, Setup will install Morrowind in the following folder.
    sleep 1000
    controlclick, Button1
    winwait, The Elder Scrolls III:  Morrowind Setup, Setup has enough information to start copying the program files.
    sleep 1000
    controlclick, Button1

    ; Then launched construction set setup
    winwait, The Elder Scrolls Construction Set Setup, The Elder Scrolls Construction Set (License Agreement)
    sleep 1000
    Controlclick, Button2
    ; No confirm screen? (FIXME: verify on windows)
    winwait, The Elder Scrolls Construction Set Setup, Setup has enough information to start copying the program files
    sleep 1000
    controlclick, Button1
    winwait, The Elder Scrolls Construction Set Setup, Setup has finished installing TES Construction Set on your computer.
    sleep 1000
    controlclick, Button4

    ; Exits the Construction set setup on its own, and goes back to main installer
    ; The text box is split into two lines separately, not using word wrap, hence the weird sentence..
    winwait, Question, Would you like to register Morrowind online now?  Make sure
    sleep 1000
    controlclick, Button7
    ; Sometimes finicky here, short sleep here works around it
    Sleep 10000
    winwait, The Elder Scrolls III:  Morrowind Setup, Setup has finished installing Morrowind on your computer.
    sleep 1000
    controlclick, Button4
    winwait, Information, You have installed Windows XP, which includes DirectX 8.1
    sleep 1000
    ControlClick, Button1
    
    exit 0"
    
    sleep 30s
    iso_umount
    cd "$olddir"
}

verblist_add orangebox     "Orange Box (Valve, 2007) " \
    976f67eec4b84331de8f6695272bc9192466da6a.iso \
    b86c9297cc4c56e98f8c3f3e489091ffa4b4a11d.iso

load_orangebox() {
    load_autohotkey

    test -f "$programfilesdir_x86_unix"/Steam/Steam.exe || sh $WINETRICKS -q steam
    # Have to log in before you can install orangebox!
    $WINE 'c:\Program Files\Steam\Steam' -login $STEAMUSER $STEAMPW
    # Now, um, let it log in for a few seconds.  Anyone know how to tell when it's done?
    sleep 45

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/976f67eec4b84331de8f6695272bc9192466da6a.iso
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/976f67eec4b84331de8f6695272bc9192466da6a.txt | tr -d -`
    ahk_do "
        SetTitleMatchMode, 2
        Run, ${ISO_MOUNT_LETTER}:Setup.exe
        winwait, ahk_class #32770
        MouseMove, 300, 365
        ; user has to click Install; I can't script it!

        ; FIXME: only do these steps on first run; if you've
        ; already activated Orange Box on your account,
        ; these don't show up.
        ;winwait, Activation
        ;MouseMove, 60, 400
        ;Click
        ;Sleep 300
        ;setKeyDelay, 300
        ;sendEvent {Raw}$KEY
        ;; Skip notice about Team Fortress guest passes
        ;winwait, News
        ;MouseMove, 650, 800
        ;Click
        ;winwait, Activation
        ;MouseMove, 310, 565
        ;Click

        winwait, Install
        sendEvent {Enter}
        ; wait for "create start menu and install" question
        sleep 5000
        sendEvent {Enter}
        winwait, Insert
    "
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/b86c9297cc4c56e98f8c3f3e489091ffa4b4a11d.iso

    ahk_do "
        SetTitleMatchMode, 2
        Send {Enter}
        winwait, ahk_class MsiDialogCloseClass, Please insert
    "
    iso_umount

    # FIXME: how to tell when update is done?  Probably have to launch all games once 
    # the the commandline option to exit immediately.
}

#----------------------------------------------------------------

verblist_add pcmark04 "PC Mark 04 (Futuremark, 2004) [download]" PCMark04_v130_installer.exe

load_pcmark04() {
    load_autohotkey

    # http://www.futuremark.com/download/pcmark04/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/PCMark04_v130_installer.exe"
    then
        die "Sorry, you have to download PCMark04_v130_installer.exe yourself and put it in $WISOTOOL_CACHE/$PACKAGE/PCMark04_v130_installer.exe"
    fi

    warn "Please don't use mouse while this installer is running.  Sorry..."
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run PCMark04_v130_installer.exe
        ; Skip past the two windows warning about WMP9 etc.
        WinWait, Information
        Send {Enter}
        WinWaitClose, Information
        WinWait, Information
        Send {Enter}

        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        Send a ; Accept
        Send {Enter} ; Next
        Sleep 3000 ; Wait for Destination window
        Send {Enter}
        Sleep 3000 ; Wait for Install window
        Send {Enter}
        ; Wait for install to finish
        WinWait, PCMark04, Registration
        ; Purchase later
        ; This window won't activate any other way!
        MsgBox, 32, , Preparing your dungeon.  Why not enjoy a delicious slime mold while you wait?, 1
        Send {Enter}
        Sleep 3000
        ; Uncheck readme
        Send {Space}
        Send {Tab}
        Send {Tab}
        Send {Enter}
    "
    if workaround_wine_bug 22402
    then
        warn "You may need to apply the patch from bug 22402 to avoid a crash in the tumbling blocks test."
    fi

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\PCMark04"
PCMark04
__EOF__
}

#----------------------------------------------------------------

verblist_add pcmark05 "PC Mark 05 (Futuremark, 2005) [download]" PCMark05_v120_1901.exe

load_pcmark05() {
    load_autohotkey

    # http://www.futuremark.com/download/pcmark05/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/PCMark05_v120_1901.exe"
    then
        download $PACKAGE http://www.bulletproofnerds.com/uploadedfiles/futuremark/PCMark05_v120_1901.exe 8636fce0e4023cd59bcf7f3e1a027e233ee81193
    fi

    warn "Don't use mouse while this installer is running.  Sorry..."
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run PCMark05_v120_1901.exe
        ; Skip past the two windows warning about WMP10 etc.
        WinWait, Information
        Send {Enter}
        WinWaitClose, Information
        WinWait, Information
        Send {Enter}

        WinWait ahk_class #32770, Welcome
        Send {Enter}
        WinWait, ahk_class #32770, License
        Send a ; Accept
        Send {Enter} ; Next
        Sleep 3000 ; Wait for 2nd Welcome window
        Send {Enter}
        Sleep 3000 ; Wait for Destination window
        Send {Enter}
        Sleep 3000 ; Wait for Install window
        Send {Enter}
        ; Wait for install to finish
        WinWait, PCMark05, Registration
        ; Purchase later
        ; This window won't activate any other way!
        MsgBox, 32, , Preparing your dungeon.  Why not enjoy a delicious slime mold while you wait?, 1
        Send {Enter}
        Sleep 2000
        ; Uncheck readme
        Send {Space}
        Send {Tab}
        Send {Tab}
        Send {Enter}
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Futuremark\PCMark05"
PCMark05
__EOF__
}

#----------------------------------------------------------------

# Not finished
#verblist_add passmark7 "Performance Test 7 (Passmark, 2010) [download]" petst.exe

load_passmark7() {
    load_autohotkey

    # http://www.passmark.com/download/pt_download.htm
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/petst.exe"
    then
        download $PACKAGE http://www.passmark.com/ftp/petst.exe 6d9db9c1bc53452cf7a2d3ad07a1195218095f8f
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run petst.exe
    "
    warn "TODO: finish."
}

#----------------------------------------------------------------

verblist_add plantsvszombies "Plants vs. Zombies (PopCap Games, 2009) [download]" PlantsVsZombiesSetup.exe

load_plantsvszombies() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/plantsvszombies/PlantsVsZombiesSetup.exe"
    then
        download plantsvszombies "http://downloads.popcap.com/www/popcap_downloads/PlantsVsZombiesSetup.exe" fcae7b8c63d9a5b5f6ed783232bc5f612fd5c963
    fi

    cd "$WISOTOOL_CACHE/plantsvszombies"
    ahk_do "
        run PlantsVsZombiesSetup.exe
        winwait, Plants vs. Zombies Installer
        send {Enter}
        winwait, Plants vs. Zombies License Agreement
        ControlClick Button1
        winwait, Plants vs. Zombies Installation Complete!
        send {Space}{Enter}
        ControlClick, x309 y278, Plants vs. Zombies Installation Complete!,,,, Pos
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\PopCap Games\Plants vs. Zombies"
PlantsVsZombies
__EOF__
}

#----------------------------------------------------------------

verblist_add popsot_demo "Prince of Persia Sands of Time Demo (Ubisoft, 2003)" \
POP_Demo_Eng.exe

load_popsot_demo()
{
    load_autohotkey
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/POP_Demo_Eng.exe" && ! test -f "$WISOTOOL_CACHE/$PACKAGE/pop_demo_eng.exe"
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        warn "You must manually download the Prince of Persia Sands of Time Demo to $WISOTOOL_CACHE/$PACKAGE/pop_demo_eng.exe; expected sha1sum ed62f4da1f898c661ca09bd4e3a22e4a983a822b"
    fi
    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        SetTitleMatchMode, 2
        run, POP_Demo_Eng.exe
        winwait, Prince of Persia, To continue
        ControlClick, Next, Prince of Persia, To continue
        winwait, Prince of Persia, License Agreement
        ControlClick, Button3, Prince of Persia
        ControlClick, Next, Prince of Persia
        sleep 1000
        IfWinExist, Minimum Configuration
        {
          send {Enter}
        }
        winwait, Prince of Persia, Choose Destination
        ControlClick, Next, Prince of Persia, Choose Destination
        winwait, Question
        ControlClick, Yes, Question
        winwait, Prince of Persia, Installing game
        winwaitclose, Prince of Persia, Installing game
        sleep 3000
        IfWinExist, Prince of Persia, Setup has detected
        {
          ControlClick, Button2, Prince of Persia, Setup has detected
          ControlClick, Next, Prince of Persia, Setup has detected
        }
        sleep 6000
        IfWinExist, register
        {
          ControlClick, OK, register
        }
        winwait, Prince of Persia, View the Readme
        ControlClick, Button1, Prince of Persia, View the Readme
        ControlClick, Finish, Prince of Persia, View the Readme 
    "
    cd "$olddir"
    warn "Once you're in the Prince of Persia game, turn off fog or you won't be able to see anything (see wine bug 17423 for explanation, but this isn't a wine bug)"
}

#----------------------------------------------------------------

verblist_add procycling08_demo "Pro Cycling Manager 2008 Demo (Cyanide, 2008) [download, broken in wine]" ProCyclingManager08_Demo.exe

load_procycling08_demo()
{
    load_autohotkey
    # FIXME sha1sum 008b91a16c388c9965faaeaaa8242409b9db56b9
    # FIXME homepage http://www.cycling-manager.com/
    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/ProCyclingManager08_Demo.exe"
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        warn "Please download the game to $WISOTOOL_CACHE/$PACKAGE/ProCyclingManager08_Demo.exe from e.g. http://www.fileplanet.com/189566/download/Pro-Cycling-Manager---Tour-de-France-2008---Demo , sha1sum should be 008b91a16c388c9965faaeaaa8242409b9db56b9"
    fi

    cd $WISOTOOL_CACHE/$PACKAGE
    ahk_do "
        SetTitleMatchMode, 2
        run, ProCyclingManager08_Demo.exe
        winwait, Pro Cycling Manager, This will
        ControlClick, TButton1, Pro Cycling Manager, This will ; Next
        winwait, Pro Cycling, License
        ControlClick, TRadioButton1, Pro Cycling, License ; Accept License
        ControlClick, TButton2, Pro Cycling, License ; Next
        winwait, Pro Cycling, following folder
        ControlClick, TButton3, Pro Cycling, following folder ; Next
        winwait, Pro Cycling, shortcuts
        ControlClick, TButton4, Pro Cycling, shortcuts ; Next
        winwait, Pro Cycling, Click Install
        ControlClick, TButton4, Pro Cycling, Click Install ; Install
        winwait, Pro Cycling, finished
        ControlClick, TButton4, Pro Cycling,  finished ; Finish
    "
    cd "$olddir"

    if workaround_wine_bug 17512
    then
        warn "This game crashes under Wine; see http://bugs.winehq.org/show_bug.cgi?id=17512"
    fi
}

#----------------------------------------------------------------

verblist_add re5bench "Resident Evil 5 Benchmark (Capcom, 2009) [download]" nzd_ResidentEvil5_Benchmark.exe

load_re5bench() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/nzd_ResidentEvil5_Benchmark.exe"
    then
        download $PACKAGE http://download.nvidia.com/downloads/nZone/demos/nzd_ResidentEvil5_Benchmark.exe 041492b9af138f67e7acf97fbd8e926dda59ab12
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run nzd_ResidentEvil5_Benchmark.exe
        WinWait ahk_class MsiDialogCloseClass 
        Sleep 1000
        Send {Enter}
        ; ControlClick Button1 ; Next.  Doesn't work?
        WinWait ahk_class MsiDialogCloseClass, License
        ControlClick Button3 ; Accept
        ControlClick Button5 ; Next
        WinWait ahk_class MsiDialogCloseClass, Destination
        ControlClick Button1 ; Next
        WinWait ahk_class MsiDialogCloseClass, Ready
        ControlClick Button1 ; Install
        WinWait ahk_class MsiDialogCloseClass, Completed
        ControlClick Button3 ; Uncheck Launch
        ControlClick Button1 ; Finish
    "

    if workaround_wine_bug 21939
    then
        try sh "$WINETRICKS" -q wmp9
    fi

    # Should run launcher.exe, but that requires .net and doesn't run on Wine
    # Should give choice of running RE5DX10.EXE, but that requires dx10, which doesn't work on Wine yet
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\CAPCOM\RESIDENT EVIL 5 Benchmark Version"
RE5DX9.EXE
__EOF__
}

#----------------------------------------------------------------

verblist_add quake3         "Quake 3 (ID Software, 1999)" 4d2102a8df3c1fea237f2a6a141346c436614d5e.iso

load_quake3() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/4d2102a8df3c1fea237f2a6a141346c436614d5e.iso
    ahk_do "
        Run ${ISO_MOUNT_LETTER}:Setup.exe
        WinWait, Quake III Arena
        ControlClick, x532 y206 ; Click Install
        WinWait, Welcome
        ControlClick, Button1 ; Click Next
        WinWait, Software License Agreement
        ControlClick, Button2 ; Click Yes
        WinWait, Setup Type
        ControlClick, Button2 ; Click Next
        WinWait, Choose Destination Location
        ControlClick, Button1 ; Click Next
        WinWait, Select Program Folder
        ControlClick, Button2 ; Click Next
        WinWait, Question, Would you like to place a Shortcut on your Desktop?
        ControlClick, Button7 ; Click No
        WinWait, Setup Complete
        ControlClick, Button3 ; Click No I will restart my computer later.
        ControlClick, Button5 ; Click Finish
    "
    iso_umount
}

#----------------------------------------------------------------

verblist_add sims3         "The Sims 3 (EA, 2009)" 8a82a067f3bb8f68d034a06954e9a16ea381958a.iso

load_sims3() {
    load_autohotkey

    if workaround_wine_bug 22350
    then
        try sh "$WINETRICKS" -q dotnet20
    fi

    if workaround_wine_bug 21517
    then
        try sh "$WINETRICKS" -q d3dx9
    fi
    
    # Get user's key
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/8a82a067f3bb8f68d034a06954e9a16ea381958a.txt | tr -d -`

    echo KEY is $KEY
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/8a82a067f3bb8f68d034a06954e9a16ea381958a.iso
    # Default lang, USA, accept defaults, uncheck EA dl mgr, uncheck readme
    ahk_do "
        run ${ISO_MOUNT_LETTER}:Sims3Setup.exe
        winwait, Choose Setup Language
        send {Enter}
        SetTitleMatchMode, 2
        winwait, - InstallShield Wizard
        sleep 1000
        ControlClick &Next >, - InstallShield Wizard
        sleep 1000
        send uuuuuu{Tab}{Tab}{Enter}
        sleep 1000
        send a{Enter}
        sleep 1000
        send {Raw}$KEY
        send {Enter}
        winwait, - InstallShield Wizard, Setup Type
        send {Enter}
        winwait, - InstallShield Wizard, Click Install to begin
        send {Enter}
        winwait, - InstallShield Wizard, EA Download Manager
        ControlClick Yes, - InstallShield Wizard
        send {Enter}
        winwait, - InstallShield Wizard, Complete
        ControlClick View the readme file, - InstallShield Wizard
        ControlClick Finish, - InstallShield Wizard
    "
    iso_umount

    cd "$programfilesdir_unix/Electronic Arts/The Sims 3/Game/Bin"
    echo "Sims3 version info:"
    cat skuversion.txt

    download sims3 http://na.llnet.eadownloads.ea.com/u/f/sims/sims3/patches/Sims3_1.6.6.002001_from_1.0.631.00001.exe 02703d296417750005326ff0d37295fa434a3f49

    cd "$WISOTOOL_CACHE"/sims3
    ahk_do "
        run Sims3_1.6.6.002001_from_1.0.631.00001.exe
        SetTitleMatchMode, 2
        winwait, - InstallShield Wizard, Complete
        ControlClick Finish, - InstallShield Wizard
    "

    # FIXME: apply next patch, too

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\CAPCOM\RESIDENT EVIL 5 Benchmark Version"
RE5DX9.EXE
__EOF__
}

#----------------------------------------------------------------

verblist_add splitsecond_demo    "Split Second Demo (Black Rock Studios, 2010) [wine bug 22865]" SplitSecond_Demo.exe

load_splitsecond_demo()
{
    load_autohotkey

    if test ! -f "$WISOTOOL_CACHE/$PACKAGE"/SplitSecond*.exe
    then
        mkdir -p "$WISOTOOL_CACHE/$PACKAGE"
        die "You must download the demo to $WISOTOOL_CACHE/$PACKAGE before running this script.  See http://www.fileplanet.com/212404/210000/fileinfo/Split/Second-Demo"
    fi

    if workaround_wine_bug 22774
    then
        echo "On wine, install takes an extra 7 minutes at the end, please be patient."
    fi

    if workaround_wine_bug 22865
    then
        echo "This game is currently unplayable on wine due to rendering problems; see winehq bug 22865."
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    exe=`ls SplitSecond*.exe`
    ahk_do "
        SetTitleMatchMode, 2
        run, "$exe"
        winwait, Split, Language
        ControlClick, Next, Split, Language
        winwait, Split, game installation
        ControlClick, Button1, Split, game installation
        winwait, Split, license
        ControlClick, Button5, Split, license
        ControlClick, Button2, Split, license
        winwait, Split, DirectX
        ControlClick, Button5, Split, DirectX
        ControlClick, Button2, Split, DirectX
        winwait, Split, installation path
        ControlClick, Button1, Split, installation path
        winwait, Split, Game features
        ControlClick, Button2, Split, Game features
        winwait, Split, start copying
        ControlClick, Button1, Split, start copying 
        winwait, Split, completed
        ControlClick, Button1, Split, completed
        ControlClick, Button4, Split, completed
    "
    cd "$olddir"
}

#----------------------------------------------------------------

verblist_add splitsecond    "Split Second (Black Rock Studios, 2010) [wine bug 22865]" 15548fabe350e1b65432400aae8c3acfb1c930d8.iso

load_splitsecond()
{
    load_autohotkey

    if workaround_wine_bug 22774
    then
        echo "On wine, install takes an extra 7 minutes at the end, please be patient."
    fi

    if workaround_wine_bug 22865
    then
        echo "This game is currently unplayable on wine due to rendering problems; see winehq bug 22865."
    fi

    #KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/15548fabe350e1b65432400aae8c3acfb1c930d8.txt`
    # Key is used in first run activation.  TODO: script first run activation.

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/15548fabe350e1b65432400aae8c3acfb1c930d8.iso

    # Aborts with dialog about FirewallInstallHelper.dll if that's not on the path (e.g. in current dir)
    cd "$ISO_MOUNT_ROOT"
    ahk_do "
        SetTitleMatchMode, 2
        run setup.exe
        winwait, Split, Language
        ControlClick, Next, Split, Language
        winwait, Split, game installation
        ControlClick, Button1, Split, game installation
        winwait, Split, license
        ControlClick, Button5, Split, license
        ControlClick, Button2, Split, license
        winwait, Split, DirectX
        ControlClick, Button5, Split, DirectX
        ControlClick, Button2, Split, DirectX
        winwait, Split, installation method
        send {Enter}
        winwait, DirectX needs to be updated
        send {Enter}
        winwait, Split, begin
        ControlClick, Button1
        winwait, Split, completed
        ControlClick, Button1, Split
        ControlClick, Button4, Split
    "
    cd "$olddir"
}

#----------------------------------------------------------------

verblist_add starcraft     "Starcraft Battle Chest (Blizzard, 1998)" 8d6cc11bc76b8af22868a95e17e0282277e9c53c.iso 966bae1f2e2035e066139e78137e623c92838254.iso

load_starcraft() {
    warn "You must have already done 'wisotool load=YOURKEY' on the install disc, and 'wisotool load' on the other disc." 
    load_autohotkey

    # Force clean-ish install
    test -d "$programfilesdir_unix/StarCraft" && rm -rf "$programfilesdir_unix/StarCraft"

    # Get user's key
    KEY=`cat "$WISOTOOL_CACHE"/$PACKAGE/8d6cc11bc76b8af22868a95e17e0282277e9c53c.txt`

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/8d6cc11bc76b8af22868a95e17e0282277e9c53c.iso
    ahk_do "
        run ${ISO_MOUNT_LETTER}:StarCraft (Windows).exe
        winwait, StarCraft - Brood War
        send {i}
        winwait, End User License Agreement
        Sleep 2000
        send {a}
        winwait, CD-Key
        send $USERNAME
        send {Tab}$KEY
        send {Enter}
        winwait, Installation Destination Directory
        send {Enter}
        winwait,,Please insert"
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/966bae1f2e2035e066139e78137e623c92838254.iso
    ahk_do "
        send, {Enter}
        SetTitleMatchMode, 2
        winwait, - StarCraft
        winwaitclose, - StarCraft
        Sleep 2000
        send {e}"
    iso_umount

    # FIXME: apply patch, follow instructions in http://us.blizzard.com/support/article.xml?articleId=21150
}

#----------------------------------------------------------------

verblist_add starcraft2    "Starcraft II beta (Blizzard, 2010)" "StarCraft II Beta enUS 13891 Installer/Installer.exe"

load_starcraft2() {
    load_autohotkey

    if test -d "$programfilesdir_unix/StarCraft II Beta"
    then
        warn "$PACKAGE already installed, skipping."
        return 0
    fi

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/StarCraft II Beta enUS 13891 Installer/Installer.exe"
    then
        die "You must have run the downloader and told it to save in $WISOTOOL_CACHE/$PACKAGE"
    fi

    if ! test -f "$WINDIR"/system32/plugin.ocx && workaround_wine_bug 22089
    then
        try sh "$WINETRICKS" -q ie6
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE/StarCraft II Beta enUS 13891 Installer"
    ahk_do "
        SetTitleMatchMode, 2
        run Installer.exe
        winwait, StarCraft II Beta Installer
        ControlClick, x300 y200
        winwait, End User License Agreement
        winactivate
        MouseMove, 300, 300
        Click WheelDown, 70
        Sleep, 1000
        ControlClick, Agree
        winwait, Installation Destination Directory
        send {Enter}
        winwait, StarCraft II v, update was successful
        winclose
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\StarCraft II Beta"
"StarCraft II.exe"
__EOF__
}

#----------------------------------------------------------------
verblist_add sto           "Star Trek Online (Cryptic, 2010)" f891dab46d05d771e0123a1e7ec969f3601064a6.iso

load_sto()
{
    load_autohotkey
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/f891dab46d05d771e0123a1e7ec969f3601064a6.iso
    # Note: http://www.startrekonline.com/download shows how to download the
    # client using bittorrent.  If the iso is not present, we should try that path.

    if workaround_wine_bug 22943
    then
        # Install is fine without ie6, but can't log in or download patch without ie6,
        # and the installer launches the app when it's done.
        # Even with ie6, it's not perfect, there are lots of annoying script error prompts.
        sh "$WINETRICKS" -q ie6
    fi

    ahk_do "
        SetTitleMatchMode, 2
        run ${ISO_MOUNT_LETTER}:setup.exe
        winwait, Installer
        Send {Enter}                        ; Accept English as default language
        winwait, Star Trek Online
        ControlClick, Button2
        winwait, Star Trek, License
        ControlClick, Button2,
        winwait, Star Trek, Location
        ControlClick, Button2
        winwait, Star Trek, shortcuts
        ControlClick, Button2
        winwait, Star Trek, additional
        ControlClick, Button2
        winwait, Star Trek, Launch
        ControlClick, Button2
    " 
    iso_umount
    # FIXME: register using the key that came with the DVD?
    # FIXME: log in and download patch?
    # FIXME: kill game?
}

#----------------------------------------------------------------

verblist_add stfu          "Starwars: The Force Unleashed (Aspyr, 2009)" 0d0f4e826c3a04542a68d7bcc971f4df7526965b.iso 5d6e2eb1b08b9d4a71b2390b385c3048ec91f3df.iso

load_stfu() {
    load_autohotkey

    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/0d0f4e826c3a04542a68d7bcc971f4df7526965b.iso
    warn "Starting installer.  This can be very slow, please be patient."
    ahk_do "
        run ${ISO_MOUNT_LETTER}:setup.exe
        SetTitleMatchMode, 2
        winwait, Select Setup Language
        send {Enter}
        winwait, Setup, Welcome
        send {Enter}
        winwait, Setup, License
        sleep 500
        send {Tab}a{Space}{Enter}
        winwait, Setup, Destination
        send {Enter}
        winwait, Setup, Menu
        send {Enter}
        winwait, Setup, Tasks
        send {Space}{Enter}
        winwait, Setup, begin
        sleep 1000
        ControlClick &Install, Setup
        winwait, Setup Needs the Next Disk
    "
    iso_umount
    iso_mount "$WISOTOOL_CACHE"/$PACKAGE/5d6e2eb1b08b9d4a71b2390b385c3048ec91f3df.iso
    ahk_do "
        SetTitleMatchMode, 2
        send {Enter}
        winwait, Setup, Completing
        send {Space}{Tab} ; don't show readme
        send {Space}{Tab} ; don't start app
        send {Enter}
    "
    iso_umount

    # Patch to 1.2
    # FIXME: add a commandline option to disable patching in general
    # URL from http://www.lucasfiles.com/index.php?s=&action=download&id=1537&agree=true 
    # See also http://www.forceunleashed.net/news/force-unleashed-patch-1-2/
    download stfu http://xfer.lfnetwork.com/lucasfiles.com/downloads/1537/SWTFU_PC_EF_1.2_Update.exe cfd8043c4b86f4dc0ff0acd4c108b11c4b76e716
    cd "$WISOTOOL_CACHE/stfu"
    ahk_do "
        run SWTFU_PC_EF_1.2_Update.exe
        SetTitleMatchMode, 2
        winwait, Patch
        send {Enter}
        winwait, Patch, Finish
        send {Enter}
    "

    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\StarCraft II Beta"
"StarCraft II.exe"
__EOF__

    # Should start SWTFU Launcher.exe, but that doesn't run in Wine?
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Aspyr\Star Wars The Force Unleashed"
SWTFU.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add unigine_heaven "Unigen Heaven 2 Benchmark (Unigen, 2010) [download]" Unigine_Heaven-2.0.msi

load_unigine_heaven() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/$PACKAGE/Unigine_Heaven-2.0.msi"
    then
        warn "This download is slow, you may want to do a manual download from http://downloads.guru3d.com/Unigine-Heaven-DirectX-11-benchmark-2.0-download-2414.html instead"
        #download $PACKAGE http://www.techpowerup.com/downloads/1775e/Unigine_Heaven-2.0.msi 6a0bd499ae8ed8d73d74d964d3c4312a0a40b7e6
        download $PACKAGE http://unigine.com/download/files/Unigine_Heaven-2.0.msi 6a0bd499ae8ed8d73d74d964d3c4312a0a40b7e6
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    ahk_do "
        run msiexec /i Unigine_Heaven-2.0.msi
        WinWait ahk_class MsiDialogCloseClass 
        Sleep 1000
        Send {Enter}
        WinWait ahk_class MsiDialogCloseClass, License
        ControlClick Button1 ; Accept
        ControlClick Button3 ; Accept
        WinWait ahk_class MsiDialogCloseClass, Choose
        ControlClick Button1 ; Typical
        WinWait ahk_class MsiDialogCloseClass, Ready
        ControlClick Button2 ; Install
        ; FIXME: on systems with OpenAL already (Win7?), the next four lines
        ; are not needed.  We should somehow wait for either OpenAL window
        ; *or* Completed window.
        WinWait ahk_class OpenAL Installer
        ControlClick Button2 ; OK
        WinWait ahk_class #32770
        ControlClick Button1 ; OK

        WinWait ahk_class MsiDialogCloseClass, Completed
        Sleep 500
        ControlClick Button1 ; Finish
        Send {Enter}
    "

    if workaround_wine_bug 22614
    then
        # hope your card actually has 1GB of RAM
        sh "$WINETRICKS" videomemorysize=1024
    fi

    # Should start Heaven.exe, but that doesn't run in Wine
    # Should give option to run Heaven_gl.bat (even works in Wine)
    # or the dx10 or dx11 versions (doesn't).
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\Unigine\Heaven"
cmd /c Heaven_d3d9.bat
__EOF__
}

#----------------------------------------------------------------

verblist_add wog           "World of Goo demo (2D Boy, 2008) [download]" WorldOfGooDemo.1.0.exe

load_wog() {
    load_autohotkey

    if ! test -f "$WISOTOOL_CACHE/wog/WorldOfGooDemo.1.0.exe"
    then
        # Get temporary download location
        download wog "http://www.worldofgoo.com/dl2.php?lk=demo&filename=WorldOfGooDemo.1.0.exe"
        URL=`cat "$WISOTOOL_CACHE/wog/dl2.php?lk=demo&filename=WorldOfGooDemo.1.0.exe" | 
           grep WorldOfGooDemo.1.0.exe | sed 's,.*http,http,;s,".*,,'`
        rm "$WISOTOOL_CACHE/wog/dl2.php?lk=demo&filename=WorldOfGooDemo.1.0.exe"
       
        download wog "$URL" e61d8253b9fe0663cb3c69018bb3d2ec6152d488
    fi

    cd "$WISOTOOL_CACHE/wog"
    ahk_do "
        run WorldOfGooDemo.1.0.exe
        winwait, World of Goo Setup, License Agreement
	send {Enter}
        winwait, World of Goo Setup, Choose Components
	send {Enter}
        winwait, World of Goo Setup, Choose Install Location
	send {Enter}
        winwait, World of Goo Setup, Thank you
	ControlClick, Make me dirty right now, World of Goo Setup, Thank you
	send {Enter}
        "
    cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__ 
cd "$programfilesdir_x86_win\WorldOfGooDemo"
WorldOfGoo.exe
__EOF__
}

#----------------------------------------------------------------

verblist_add wowbc       "World of Warcraft: Battle Chest (Blizzard, 2008)" \
  c874f5bc676eef8e60d3d232fe6db185c4632fb3.iso

load_wowbc() {
    load_autohotkey
    test -f "$WINDIR"/utorrent.exe || try sh $WINETRICKS utorrent

    case "$LANG" in
    en_US*) ;;
    *) die "This script probably only works for World of Warcraft in the enUS locale."
    esac

    # Torrent file URLs found on http://www.wowwiki.com/Patch_mirrors
    # Patch 3.3.2.11403-to-3.3.3.11685-enUS-patch.exe is downloaded from http://alexsmith.im/wow-patches/enus-patches
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.x.x.x-3.2.0.10192-x86-Win-enUS.torrent" f9e96e7b4edc6a4c22faad084eef147853e3ebb5
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.2.0.10192-3.3.0.10958-x86-Win-enUS.torrent" 33bdf8749b3c3781451b5f6ac2a59ba29d6c61bd
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.3.0.10958-3.3.0.11159-x86-Win-enUS.torrent" b7ad37a75713f6d8e578558ca1e321927192c6c6
    download $PACKAGE "http://a.wirebrain.de/wow/torrent/WoW-3.3.0.11159-to-3.3.2.11403-enUS-patch.torrent" f73763541197fecdcca9b9f8cf91e83cde989a49
    download $PACKAGE "http://uk1.files.alexsmith.im/enUS/WoW-3.3.2.11403-to-3.3.3.11685-enUS-patch.exe" ce73a0a8aa9f6eaf00b5e7cd0a34eb928738fd36
    download $PACKAGE "http://server1.fiberdownload.com/7_kituri/World-of-Warcraft.zip" 76d3c7f1c034e5533132e610b2e1b8f376893fdc

    cd "$WISOTOOL_CACHE/$PACKAGE"
    try unzip -quo World-of-Warcraft.zip
    patch1=`stat -Lc%s WoW-3.2.0-enUS-patch.exe`
    patch2=`stat -Lc%s WoW-3.2.0.10192-to-3.3.0.10958-enUS-patch.exe`
    patch3=`stat -Lc%s WoW-3.3.0.10958-to-3.3.0.11159-enUS-patch.exe`
    patch4=`stat -Lc%s WoW-3.3.0.11159-to-3.3.2.11403-enUS-patch.exe`
    patch5=`stat -Lc%s WoW-3.3.2.11403-to-3.3.3.11685-enUS-patch.exe`
    patch6=`stat -Lc%s WoW-3.3.3.11685-to-3.3.3.11723-enUS-patch.exe`

    if  [ $patch5 -ne 128600432 ] || [ $patch6 -ne 4959280 ]
    then
        die "Failed to download patch 3.3.3.11685 or patch 3.3.3.11723"
    fi

    if [ $patch1 -eq 1323316774 ] && [ $patch2 -eq 572045930 ] && [ $patch3 -eq 5101376 ] && [ $patch4 -eq 167050587 ]
    then
        echo "All patches have been downloaded"
    else
        UT_WINPATH="$WISOTOOL_CACHE_WIN\\wowbc"
        for torrent in `ls *.torrent`
        do
            try $WINE utorrent "/DIRECTORY" "$UT_WINPATH" "$UT_WINPATH\\$torrent" &
        done
    
        # Start uTorrent, have it wait until all downloads are finished
        ahk_do "
            SetTitleMatchMode, 2
            winwait, Torrent
            winwait, Torrent, default
            controlclick, Button7, Torrent, default
            send !o
            send a{Down}{Enter}
            winwaitclose, Torrent
        "
    fi
    cd "$olddir"

    if ! test -d "$WISOTOOL_CACHE"/$PACKAGE/tempcd
    then
        try mkdir -p "$WISOTOOL_CACHE"/$PACKAGE/tempcd
        iso_mount "$WISOTOOL_CACHE"/$PACKAGE/c874f5bc676eef8e60d3d232fe6db185c4632fb3.iso
        sleep 5
        try cp -r "$ISO_MOUNT_ROOT"/* "$WISOTOOL_CACHE"/$PACKAGE/tempcd
    fi

    # Checks if WoW is installed. If so, skips primary install and proceeds to applying patches
    if ! test -d "$DRIVE_C/Program Files/World of Warcraft"
    then
      ahk_do "
          run "$WISOTOOL_CACHE"/$PACKAGE/tempcd/Installer.exe
          SetTitleMatchMode, 2
          winwait, Burning Crusade Installer
          sleep 4000
          send b
          sleep 2000
          send o
          winwait, License Agreement
          winactivate
          MouseMove, 300, 300
          Click WheelDown, 90
          Sleep, 2000
          ControlClick, Button1
          winwait, Installation Destination Directory
          send {Enter}
          winwait, Manage
          ControlClick, Button2
	  Loop
          {
              ; World Of Warcraft directory is created as .temp, then renamed when done
              ifExist, C:\Program Files\World of Warcraft\Logs\Burning Crusade Install Log.html
                   break
              Sleep 10000
          }
          "
       killall Launcher.exe
       killall Installer.exe
    fi

    cd "$WISOTOOL_CACHE/$PACKAGE"
    for file in \
        WoW-3.2.0-enUS-patch.exe\
        WoW-3.2.0.10192-to-3.3.0.10958-enUS-patch.exe\
        WoW-3.3.0.10958-to-3.3.0.11159-enUS-patch.exe\
        WoW-3.3.0.11159-to-3.3.2.11403-enUS-patch.exe\
        WoW-3.3.2.11403-to-3.3.3.11685-enUS-patch.exe\
        WoW-3.3.3.11685-to-3.3.3.11723-enUS-patch.exe

    do
        ahk_do "
           run "$WISOTOOL_CACHE"/$PACKAGE/$file
           SetTitleMatchMode, 2
           winwait, Blizzard Updater
           IfWinExist, Blizzard Updater, unable to start ;Exit if patch is already applied 
           {
             ControlClick, Button1, Blizzard Updater, unable to start
             exit
           }
           else
           {
             winwait, Blizzard Updater, The update was successful
             ControlClick, Button1
             winwait, Launcher
             winkill, Launcher
             winwait, World of Warcraft
             sleep 5000 ; Give time for Play button to appear
             IfWinExist, World of Warcraft, Play ;Exit if last patch is applied
             {
               ; Done!  No more patches.
               winkill, World of Warcraft, Play
             }
             else
             {
               ; Don't let it download the next patch
               winwait, World of Warcraft, Estimated time
               winkill, World of Warcraft, Estimated time
             }
           }
        "
        echo "Patched $file"
        sleep 5
    done
}

#----------------------------------------------------------------

# Generic GOG.com installer
# Usage: game_id game_title [other_files,size [reader_control [run_command [download_id [install_dir [installer_size_and_sha1]]]]]]
# game_id
#     Used for main installer name and download url.
# game_title
#     Used for AutoHotKey and installation path in bat script.
# other_files
#     Extra installer files, in one string, space-separated.
# reader_control
#     If set, the control id of the configuration pannel checkbox controling
#     Adobe Reader installation.
#     Some games don't have it, some games do with different ids.
# run_command
#     Used for bat script, relative to installation path.
# download_id
#     For games which download url doesn't match their game_id
# install_dir
#     If different from game_title
# installer_size_and_sha1
#     exe file SHA1.
_load_gog()
{
    load_autohotkey

    game_id="$1"
    game_title="$2"
    other_files="$3"
    reader_control="$4"
    run_command="$5"
    download_id="$6"
    install_dir="$7"
    installer_size_and_sha1="$8"

    if [ "$download_id"x = ""x ]
    then
        download_id="$game_id"
    fi
    if [ "$install_dir"x = ""x ]
    then
        install_dir="$game_title"
    fi

    installer_path="$WISOTOOL_CACHE/$PACKAGE"
    mkdir -p "$installer_path"
    auth_path="$WISOTOOL_CACHE/gog_auth"
    mkdir -p "$auth_path"
    installer="setup_$game_id.exe"
    cookie="$auth_path/cookie.txt"

    if test "$installer_size_and_sha1"x == ""x
    then
        files="$installer $other_files"
    else
        files="$installer,$installer_size_and_sha1 $other_files"
    fi

    file_id=0
    for file_and_size_and_sha1 in $files
    do
        case "$file_and_size_and_sha1" in
        *,*,*)
            sha1sum=`echo $file_and_size_and_sha1 | sed "s/.*,//"`
            minsize=`echo $file_and_size_and_sha1 | sed 's/[^,]*,\([^,]*\),.*/\1/'`
            file=`echo $file_and_size_and_sha1 | sed 's/,.*//'`
            ;;
        *,*) 
            sha1sum=""
            minsize=`echo $file_and_size_and_sha1 | sed 's/.*,//'`
            file=`echo $file_and_size_and_sha1 | sed 's/,.*//'`
            ;;
        *)
            sha1sum=""
            minsize=1
            file=$file_and_size_and_sha1
            ;;
        esac
        file_path="$installer_path/$file"
        if ! test -s "$file_path" || test `stat -Lc%s "$file_path"` -lt $minsize
        then
            if ! grep "GOGcom_usr" "$cookie" > /dev/null 2>&1
            then
                login_file="$auth_path/login.txt"
                password_file="$auth_path/password.txt"
                if ! test -f "$login_file" -a -f "$password_file"
                then
                    die "Please put your GOG.com login in '$login_file' and password in '$password_file' or put '$file' in '$installer_path'."
                fi
                if ! grep "@" "$login_file" > /dev/null 2>&1
                then
                    die "$login_file must contain your GOG.com login, which is an e-mail address (as opposed to account name)."
                fi
                base_url="https://www.gog.com"
                login_url="/en/login/ajax/"
                next_url="$WISOTOOL_TMP/gog_redir_url"
                post_data="$WISOTOOL_TMP/gog_post_data"
                login="`url_encode < \"$login_file\"`"
                status=$?
                if test $status -ne 0
                then
                     die "Note: login escaping failed with status $status.  Aborting"
                fi
                password="`url_encode < \"$password_file\"`"
                status=$?
                if test $status -ne 0
                then
                     die "Note: password escaping failed with status $status.  Aborting"
                fi
                # Note: just write login & password to a file so they don't appear in "ps"
                echo "a=check&t=old&u=$login&p=$password&r=frontpage" > "$post_data"
                if test -x "`which wget 2>/dev/null`"
                then
                    try wget -O "$next_url" --save-cookies "$cookie" --post-file "$post_data" "$base_url$login_url"
                    try wget -O /dev/null --load-cookies "$cookie" --save-cookies "$cookie" "$base_url`cat \"$next_url\"`"
                else
                    try curl -o "$next_url" --cookie-jar "$cookie" --data "@$post_data" "$base_url$login_url"
                    try curl -o /dev/null --cookie "$cookie" --cookie-jar "$cookie" "$base_url`cat \"$next_url\"`"
                fi
                rm -f "$post_data"
                rm -f "$next_url"
            fi
            nosizecheck=1
            download "$PACKAGE" "https://www.gog.com/en/download/game/$download_id/$file_id" "" "$file" "$cookie"
            unset nosizecheck
            check_sha1=1
            filesize=`stat -Lc%s "$file_path"`
            if test $minsize -gt 1 -a $filesize -ne $minsize
            then
                check_sha1=""
                warn "Expected file size $minsize, please report new size $filesize."
            fi
            if test "$check_sha1" != "" -a "$sha1sum"x != ""x
            then
                verify_sha1sum "$sha1sum" "$file_path"
            fi
        fi
        file_id=`expr $file_id + 1`
    done

    cd "$installer_path"
    ahk_do "
        run $installer
        WinWait, Setup - $game_title, Start installation
        ControlGet, checkbox_state, Checked,, TCheckBox1 ; EULA
        if (checkbox_state != 1) {
            ControlClick, TCheckBox1
        }
        if (\"$reader_control\") {
            ControlClick, TMCoPShadowButton1 ; Options
            Loop, 10
            {
                ControlGet, visible, Visible,, $reader_control
                if (visible)
                {
                    break
                }
                Sleep, 1000
            }
            ControlGet, checkbox_state, Checked,, $reader_control ; Unckeck Adobe/Foxit Reader
            if (checkbox_state != 0) {
                ControlClick, $reader_control
            }
        }
        ControlClick, TMCoPShadowButton2 ; Start Installation
        WinWait, Setup - $game_title, Exit Installer
        ControlClick, TMCoPShadowButton1 ; Exit Installer
        "

    if [ "$run_command"x != ""x ]
    then
        cat > "$DRIVE_C/run-$PACKAGE.bat" <<__EOF__
cd "$programfilesdir_x86_win\\GOG.com\\$install_dir"
$run_command
__EOF__
    fi
}

verblist_add dukenukem3d_gog "Duke Nukem 3D (GOG.com)" setup_duke3d.exe

load_dukenukem3d_gog()
{
    _load_gog "duke3d" "Duke Nukem 3D" "" "TsCheckBox2" "DOSBOX\\dosbox.exe -conf dosboxDuke3D.conf -noconsole -c \"exit\"" "duke_nukem_3d_atomic_edition" "" "28863130,0b86cb60aa2549a46b1bf099a5b544d198ccebaa"
}

verblist_add dukenukemmp_gog "Duke Nukem Manhattan Project (GOG.com)" setup_duke_nukem_manhattan_project.exe

load_dukenukemmp_gog()
{
    _load_gog "duke_nukem_manhattan_project" "Duke Nukem - Manhattan Project" "" "TsCheckBox2" "DukeNukemMP.exe" "" "" "212465575,ffabbc2e96c2c85c4fe8c519afdde2a5226e5ce6"
}

verblist_add ut2004_gog "Unreal Tournament 2004 (GOG.com)" setup_ut2004.exe setup_ut2004-1.bin setup_ut2004-2.bin

load_ut2004_gog()
{
    _load_gog "ut2004" "Unreal Tournament 2004" "setup_ut2004-1.bin,2097510656,77a17856d77545e7930471a3fe3ce210a649edcd setup_ut2004-2.bin,3010009,f327498d0e1f6332d25c18629d277435a6c292da" "TsCheckBox2" "system\\ut2004.exe" "unreal_tournament_2004_ece" "" "2489303,67dfcf2ffa74123436d2cbc010e21d48860ea995"
}

verblist_add abes_oddysee_gog "Abes Oddysee (GOG.com)" AbeWin.exe setup_abes_oddysee.exe

load_abes_oddysee_gog()
{
    _load_gog "abes_oddysee" "Abe's Oddysee" "" "TsCheckBox2" "AbeWin.exe" "oddworld_abes_oddysee" "" "380905004,848b41ac4aaea0e13e5d609bcdc6fe4c9db2368f"
}

verblist_add abes_exoddus_gog "Abes Exoddus (GOG.com)" Exoddus.exe setup_abes_exoddus.exe

load_abes_exoddus_gog()
{
    _load_gog "abes_exoddus" "Abe's Exoddus" "" "TsCheckBox2" "Exoddus.exe" "oddworld_abes_exoddus" "" "625840158,a8f110038c387afa59b0277c2f68dd5e4c27478c"
}

verblist_add beyond_good_and_evil_gog "Beyond Good and Evil (GOG.com)" setup_beyond_good_and_evil.exe

load_beyond_good_and_evil_gog()
{
    _load_gog "beyond_good_and_evil" "Beyond Good and Evil" "" "TsCheckBox2" "gogwrap.exe GOGBEYONDGOODANDEVIL" "" "" "1544566386,cba7c1647c217cfa2db4f770bee35be88b2f08c6"
}

verblist_add far_cry_gog "Far Cry (GOG.com)" setup_far_cry.exe setup_far_cry-1.bin setup_far_cry-2.bin

load_far_cry_gog()
{
    _load_gog "far_cry" "Far Cry" "setup_far_cry-1.bin,2097392384,01819fd08cda4ba5ace4731858e79ef0f5fceca6 setup_far_cry-2.bin,437651497,3796bbd0cb626496fe7cfdd930061821e931fcb5" "TsCheckBox2" "Bin32\\FarCry.exe" "" "" "2607407,0ed9a8976868d2aac1b66a2e216c3d7acac1c3c9"
}

verblist_add descent_1_2_gog "Descent and Descent 2 (GOG.com)" setup_descent_1_2.exe

load_descent_1_2_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "descent_1_2" "Descent and Descent 2" "" "TsCheckBox5" "" "descent_1_descent_2" "" "577588226,a8f64b537bb3c58aab5955ab92a3e9f6831024fe"
}

verblist_add descent_3_gog "Descent 3 (GOG.com)" setup_descent_3.exe

load_descent_3_gog()
{
    _load_gog "descent_3" "Descent 3 and Mercenary Expansion" "" "TsCheckBox4" "Descent 3.exe" "descent_3_expansion" "Descent 3" "837442501,41342901910aa3d973ef0778cbc9f0d43d5713e9"
}

verblist_add evil_genius_gog "Evil Genius (GOG.com)" setup_evil_genius.exe

load_evil_genius_gog()
{
    _load_gog "evil_genius" "Evil Genius" "" "TsCheckBox2" "ReleaseExe\\EvilGeniusExeStub-Release.exe" "" "" "1394559416,d0bc345e44cd202daa4243315fbb529c042174e0"
}

verblist_add psychonauts_gog "Psychonauts (GOG.com)"  setup_psychonauts.exe

load_psychonauts_gog()
{
    _load_gog "psychonauts" "Psychonauts" "setup_psychonauts-1.bin,2097627392,ba141083b6ac3d82b6e9bf72332d8876c7566378 setup_psychonauts-2.bin,765732413,bef1f8b19c2700e7c81d9aa8a21358266eafe8c9" "TsCheckBox2" "Psychonauts.exe" "" "" "2372340,04f3d2bfb36bb4d7bf5f2800837e218f6a034f4b"
}

verblist_add ut_goty_gog "Unreal Tournament GOTY (GOG.com)" setup_ut_goty.exe

load_ut_goty_gog()
{
    # XXX: Installer window contains: "Unreal Tournament", 2 spaces, a long dash, 1 space "Game Of The Year Edition"
    _load_gog "ut_goty" "Unreal Tournament  " "" "TsCheckBox2" "gogwrap.exe GOGUT" "unreal_tournament_goty" "Unreal Tournament GOTY" "336712863,bd464862181f9a4386e3d10bee616277ecf7e060"
}

verblist_add unreal_gold_gog "Unreal Gold Edition (GOG.com)" setup_unreal_gold.exe

load_unreal_gold_gog()
{
    _load_gog "unreal_gold" "Unreal Gold" "" "TsCheckBox2" "gogwrap.exe GOGUNREAL" "" "" "251958142,189709657792ec89f534b52f31dbe3aba2c6040b"
}

verblist_add unreal_2_se_gog "Unreal 2: The awakening Special Edition (GOG.com)" setup_unreal2_se.exe

load_unreal_2_se_gog()
{
    # \x96 is ansi-1250 for "en dash"
    _load_gog "unreal2_se" "Unreal 2 `echo -e '\x96'` The Awakening Special Edition" "" "TsCheckBox4" "gogwrap.exe GOGUNREAL2" "unreal_2_the_awakening_se" "" "1312187483,0a685f43eb4dcb28e5b8f7f46ff20f05c0082311"
}

verblist_add battle_chess_gog "Battle Chess (GOG.com)" setup_battle_chess.exe

load_battle_chess_gog()
{
    # XXX: this installs 3 games, how should bat script be ?
    _load_gog "battle_chess" "Battle Chess Special Edition" "" "TsCheckBox5" "" "battle_chess_special_edition" "" "46082407,258e74d9a4a2d9d3bd0e261c2a5b229c2b475b9c"
}

verblist_add earth_2150_trilogy_gog "Earth 2150 trilogy (GOG.com)" setup_earth_2150_trilogy.exe

load_earth_2150_trilogy_gog()
{
    # XXX: this installs 3 games, how should bat script be ?
    _load_gog "earth_2150_trilogy" "Earth 2150 Trilogy" "" "TsCheckBox4" "" "" "" "1678391114,898711e463f78182cc008713e0a5be81ead060f0"
}

verblist_add earth_2160_gog "Earth 2160 (GOG.com)" setup_earth_2160.exe

load_earth_2160_gog()
{
    _load_gog "earth_2160" "Earth 2160" "" "TsCheckBox2" "Earth2160_START.exe" "" "" "912927726,5b59076ff5293456ed5043e130bf95e406e1dd73"
}

verblist_add empire_earth_gold_gog "Empire Earth Gold (GOG.com)" setup_empire_earth_gold.exe

load_empire_earth_gold_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "empire_earth_gold" "Empire Earth Gold Edition" "" "TsCheckBox4" "" "empire_earth_gold_edition" "" "564162686,4fdc33fb072923d36749230df52d28fba3fcefe7"
}

verblist_add earthworm_jim_1_2_gog "Earthworm Jim 1 & 2 (GOG.com)" setup_ewj_1_2.exe

load_earthworm_jim_1_2_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "ewj_1_2" "Earthworm Jim 1 and 2" "" "TsCheckBox5" "" "earthworm_jim_1_2" "" "622331530,0cf7876691c7fecbe017e7518fd6aab0417ab783"
}

verblist_add shogo_gog "Shogo Mobile Armor Division (GOG.com)" setup_shogo.exe

load_shogo_gog()
{
    # \x96 is ansi-1250 for "en dash"
    _load_gog "shogo" "Shogo `echo -e '\x96'` Mobile Armor Division" "" "TsCheckBox2" "Shogo.exe" "shogo_mobile_armor_division" "" "262247809,9ca006401565a8bf45363c943a4c3cb0b09bec4b"
}

verblist_add settlers_2_gold_gog "The Settlers 2 Gold (GOG.com)" setup_settlers_2_gold.exe

load_settlers_2_gold_gog()
{
    _load_gog "settlers_2_gold" "Settlers 2 GOLD" "" "TsCheckBox2" "DOSBOX\\dosbox.exe -conf dosboxSettlers2.conf -noconsole -c \"exit\"" "the_settlers_2_gold_edition" "" "286716917,efe390e48867edc3840b0d7c9cbab35ea8639b0c"
}

verblist_add robinson_requiem_collection_gog "Robinson Requiem & Deus (GOG.com)" setup_robinson_requiem_collection.exe

load_robinson_requiem_collection_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "robinson_requiem_collection" "Robinson's Requiem Collection" "" "TsCheckBox5" "" "robinsons_requiem_collection" "" "377524884,d7616bf701da1b48ca4dce4361f96f3d7aefea6d"
}

verblist_add redneck_rampage_gog "Redneck Rampage (GOG.com)" setup_redneck_rampage.exe

load_redneck_rampage_gog()
{
    # XXX: this installs 3 games, how should bat script be ?
    _load_gog "redneck_rampage" "Redneck Rampage Collection" "" "TsCheckbox5" "" "redneck_rampage_collection" "" "636962785,ca1d8c1f276db37b8dc6f93890e09161f990733a"
}

verblist_add praetorians_gog "Praetorians (GOG.com)" setup_praetorians.exe

load_praetorians_gog()
{
    _load_gog "praetorians" "Praetorians" "" "TsCheckBox2" "Praetorians.exe" "" "" "507093445,69da99ab6910550bcb3181df99c8565f99a6c193"
}

verblist_add perimeter_gog "Perimeter (GOG.com)" setup_perimeter.exe

load_perimeter_gog()
{
    _load_gog "perimeter" "Perimeter" "" "TsCheckBox2" "perimeter.exe" "" "" "1340470012,64af926cc8dacda4b9c90efaf16e2e329b5532a7"
}

verblist_add painkiller_black_gog "Painkiller Black (GOG.com)" setup_painkiller_black.exe setup_painkiller_black-1.bin setup_painkiller_black-2.bin

load_painkiller_black_gog()
{
    _load_gog "painkiller_black" "Painkiller Black" "setup_painkiller_black-1.bin,2097647872,f863652603d2a75c746d62c0eddea0a00c7f3fbc setup_painkiller_black-2.bin,1710374334,e1f0e1b648752b8b0ac88c1b715a8a7ba72e85c4" "TsCheckBox2" "bin\\Painkiller.exe" "painkiller" "" "2351728,3648b6b598e2f600fbc711d66a7122c27d7cbbfc"
}

verblist_add operation_flashpoint_goty_gog "Operation Flashpoint GOTY (GOG.com)" setup_operation_flashpoint_goty.exe

load_operation_flashpoint_goty_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    # \x96 is ansi-1250 for "en dash"
    _load_gog "operation_flashpoint_goty" "Operation Flashpoint `echo -e '\x96'` Game of the Year Edition" "" "TsCheckBox2" "" "" "Operation Flashpoint - GOTY" "769403166,13152a02cc05915f1058b6357c1621aa6c759b62"
}

verblist_add neighbours_from_hell_compilation_gog "Neighbours From Hell 1 & 2 (GOG.com)" setup_neighbours_from_hell_compilation.exe

load_neighbours_from_hell_compilation_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "neighbours_from_hell_compilation" "Neighbours From Hell Compilation" "" "TsCheckBox4" "" "" "" "373250380,fc7217f7536d0b6fcaef5111b32252bf707f0019"
}

verblist_add mdk_gog "MDK (GOG.com)" setup_mdk.exe

load_mdk_gog()
{
    _load_gog "mdk" "MDK" "" "TsCheckBox4" "gogwrap.exe GOGMDK" "" "" "104786630,0e68fc7a233a8549716d14244f4fc48ef31229e9"
}

verblist_add mdk2_gog "MDK 2 (GOG.com)" setup_mdk_2.exe

load_mdk2_gog()
{
    _load_gog "mdk_2" "MDK 2" "" "TsCheckBox2" "MDK2.exe" "" "" "231939898,e407fc49b06c8332f862b2a952aa62729c7c2388"
}

verblist_add ground_control_2_gog "Ground Control 2 (GOG.com)" setup_ground_control_2.exe

load_ground_control_2_gog()
{
    _load_gog "ground_control_2" "Ground Control II" "" "TsCheckBox2" "gcii.exe" "ground_control_2_operation_exodus" "" "641603732,b2466dd94e5e364e77ba042dc7d33088ffce585f"
}

verblist_add ghost_master_gog "Ghost Master (GOG.com)" setup_ghost_master.exe

load_ghost_master_gog()
{
    _load_gog "ghost_master" "Ghost Master" "" "TsCheckBox2" "ghost.exe" "" "" "537093924,65f89611eaba132c64bac0d1639407419a6628b2"
}

verblist_add freespace_gog "Freespace (GOG.com)" setup_freespace.exe

load_freespace_gog()
{
    _load_gog "freespace" "Freespace with Silent Threat Expansion" "" "TsCheckBox4" "fs.exe" "freespace_expansion" "Freespace" "871259230,99188805dab6b0b67d01b1fb07cf3f6f42334240"
}

verblist_add freespace_2_gog "Freespace 2 (GOG.com)" setup_freespace_2.exe

load_freespace_2_gog()
{
    _load_gog "freespace_2" "Freespace 2" "" "TsCheckBox2" "fs2.exe" "" "" "1669384651,09d2132a413aa76eaab251724ba756409fc0225a"
}

verblist_add flatout_gog "FlatOut (GOG.com)" setup_flatout.exe

load_flatout_gog()
{
    _load_gog "flatout" "FlatOut" "" "TsCheckBox2" "flatout.exe" "" "" "945261967,43e5e28a0a0c9541bbb4f4c664336442903483b3"
}

verblist_add earthworm_jim_3d_gog "Earthworm Jim 3D (GOG.com)" setup_ewj3d.exe

load_earthworm_jim_3d_gog()
{
    _load_gog "ewj3d" "Earthworm Jim 3D" "" "TsCheckBox2" "gogwrap.exe GOGEARTHWORMJIM3D" "earthworm_jim_3d" "" "144186449,3283ce57e845b111afa6df8c315bb57891046678"
}

verblist_add fallout_gog "Fallout (GOG.com)" setup_fallout.exe

load_fallout_gog()
{
    _load_gog "fallout" "Fallout" "" "TsCheckBox2" "falloutw.exe" "" "" "531198473,4c61f9e386dcfd38e55564a0bac26d5a1a8bd52a"
}

verblist_add fallout_2_gog "Fallout 2 (GOG.com)" setup_fallout_2.exe

load_fallout_2_gog()
{
    _load_gog "fallout_2" "Fallout 2" "" "TsCheckBox2" "fallout2.exe" "" "" "609017688,501a8bff61bc03643d32781d0b6b4d9f358fe863"
}

verblist_add fallout_tactics_gog "Fallout Tactics (GOG.com)" setup_fallout_tactics.exe

load_fallout_tactics_gog()
{
    _load_gog "fallout_tactics" "Fallout Tactics" "" "TsCheckBox2" "BOS.exe" "" "" "1629699801,a142ebb287d60e6ba619c8c67ec61270a3313dd3"
}

verblist_add tex_murphy_1_and_2_gog "Tex Murphy 1 & 2 (GOG.com)" setup_tex_murphy_1_and_2.exe

load_tex_murphy_1_and_2_gog()
{
    # XXX: this installs 2 games, how should bat script be ?
    _load_gog "tex_murphy_1_and_2" "Tex Murphy 1 and 2" "" "TsCheckBox5" "" "tex_murphy_1_2" "" "29082356,7aaaa686fdf424fd403bc972cbc94464a2693ce3"
}

#----------------------------------------------------------------

print_version() {
    echo "$VERSION"
}

#--------- Main program -----------------------------------------

olddir=`pwd`
srcdir=`dirname $0`
srcdir=`cd $srcdir; /bin/pwd`

# Load external verbs.  Filenames may not contain spaces.
if cd "$WISOTOOL_VERBS"
then
    for file in `find . -type f -name '*.verb' 2>/dev/null` 
    do
       . $file
    done
fi
cd "$olddir"

verblist_finish

# On Solaris, choose more modern commands (needed for id -u).
case `uname -s` in
SunOS) PATH="/usr/xpg6/bin:/usr/xpg4/bin:$PATH"
      ;;
esac

case "$1" in
-V|--version)
    echo "wisotool version $VERSION.  (C) 2007-2010 Dan Kegel et al.  LGPL."
    exit 0
    ;;
esac

detect_menu
detect_sudo

GUI=0
case x"$1" in
x) GUI=1 ;;
x-h|x--help|xhelp) usage ; exit 1 ;;
esac

case "$OS" in
 "Windows_NT")
  ;;
 *)
  # Prevent running with wrong user id.
  # It's bad to create files as the wrong user!
  die_if_user_not_dirowner "$WINEPREFIX"

  if [ ! -x "`which "$WINE" 2>/dev/null`" ]
  then
      die "Cannot find wine ($WINE)"
  fi

  # Create wineprefix if not already there
  test -d "$WINEPREFIX" || WINEDLLOVERRIDES=mshtml= $WINE cmd /c echo yes > /dev/null 2>&1
  ;;
esac

mkdir -p "$WISOTOOL_TMP"

case $GUI in
1) showmenu ; set $todo ;;
esac

mkdir -p "$WISOTOOL_CACHE"

WINETRICKS="$srcdir/winetricks"
if ! test -f "$WINETRICKS"
then
    WINETRICKS="$WISOTOOL_CACHE/winetricks"
    download . http://kegel.com/wine/winetricks
fi

# The folder-name is localized!
programfilesdir_win="`unset WINEDEBUG; WINEDLLOVERRIDES=mshtml= $WINE cmd.exe /c echo "%ProgramFiles%" | tr -d '\015'`"
test x"$programfilesdir_win" != x || die "$WINE cmd.exe /c echo '%ProgramFiles%' returned empty string"
programfilesdir_unix="`unset WINEDEBUG; $XXXPATH -u "$programfilesdir_win" | tr -d '\015' `"
test x"$programfilesdir_unix" != x || die "winepath -u $programfilesdir_win returned empty string"
wisotool_tmp_win="`$XXXPATH -w "$WISOTOOL_TMP"`"

# 64 bit windows has a second directory for program files
programfilesdir_x86_win="${programfilesdir_win} (x86)"
programfilesdir_x86_unix="${programfilesdir_unix} (x86)"
if ! test -d "$programfilesdir_x86_unix"
then
    programfilesdir_x86_win="${programfilesdir_win}"
    programfilesdir_x86_unix="${programfilesdir_unix}"
fi
export programfilesdir_x86_unix

# (Fixme: get fonts path from SHGetFolderPath
# See also http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx)
#
# Did the user rename Fonts to fonts?
if test ! -d "$WINDIR"/Fonts && test -d "$WINDIR"/fonts
then
    winefontsdir="$WINDIR"/fonts
else
    winefontsdir="$WINDIR"/Fonts
fi

# Mac folks tend to not have sha1sum, but we can make do with openssl
if [ -x "`which sha1sum 2>/dev/null`" ]
then
   SHA1SUM="sha1sum"
elif [ -x "`which openssl 2>/dev/null`" ]
then
   SHA1SUM="openssl dgst -sha1"
else
   die "No sha1sum utility available."
fi

if [ ! -x "`which unzip 2>/dev/null`" ]
then
    die "Cannot find unzip.  Please install it (e.g. 'sudo apt-get install unzip' or 'sudo yum install unzip')."
fi

while test "$1" != ""
do
    PACKAGE=$1
    case $1 in
    -q) WISOTOOL_QUIET="/q"
        WINEDEBUG=${WINEDEBUG:-"fixme-all"}
        export WINEDEBUG
        ;;
    -v) set -x;;
    ls) list_available_verbs;;
    load) load_iso dd;;
    load_harder) load_iso ddrescue;;
    load=*) key="`echo $1 | sed 's/load=//'`"; load_iso dd "$key";;
    migrate) migrate_files;;
    version) print_version;;

    *) if verblist_is_legal_verb $1
       then
           load_$1
       else
           echo Unknown arg $1; usage ; exit 1;
       fi
       ;;
    esac
    # Provide a bit of feedback
    test "$WISOTOOL_QUIET" = "" && case $1 in
    -q) echo Setting quiet mode;;
    -v) echo Setting verbose mode;;
    *) #echo "$1 done" ;;
    esac
    shift

    # User-specific postinstall hook.  
    # Source it so the script can call download() if needed.
    if [ -f "$WISOTOOL_POST"/$PACKAGE/$PACKAGE-postinstall.sh ]
    then
        ( . "$WISOTOOL_POST"/$PACKAGE/$PACKAGE-postinstall.sh )
    fi
done

test "$WISOTOOL_CACHE_SYMLINK" && rm -f "$WISOTOOL_CACHE_SYMLINK"

# remove the temp directory
chmod -R 700 "$WISOTOOL_TMP"
rm -rf "$WISOTOOL_TMP"
